2014-09-30 76 views
0

我创建链接按钮,如果点击它,它会自动添加带有删除链接的文本框。问题出在文本框和删除链接被添加后,当单击删除链接时,它不能删除文本框。如何解决这个问题?如何删除使用jquery运行时创建的文本框

查看

@using (Html.BeginForm()) 
{ 
    <div id="editorRows"> 
     @foreach (var item in Model) 
     { 
      Html.RenderPartial("GiftEditorRow", item); 
     } 
    </div> 
    @Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" }) 
    <input type="submit" value="Finished" /> 
} 

@section Scripts { 
    <script> 
     $(document).ready(function() { 
      $("#addItem").click(function() { 
       $.ajax({ 
        url: this.href, 
        cache: false, 
        success: function (html) { 
         $("#editorRows").append(html); 
        } 
       }); 
       return false; 
      }); 

      $("a.deleteRow").on("click", function() { 
       $(this).parents("div.editorRow:first").remove(); 
       return false; 
      }); 
     }); 
    </script> 
} 

部分用于动态添加文本框查看:

@model MvcApplication1.Models.Gift 
@using MvcApplication1.Helpers 

<div class="editorRow"> 
    @using (Html.BeginCollectionItem("gifts")) 
    { 
     <p> 
      Item: @Html.TextBoxFor(x => x.Name) 
      Value: @Html.TextBoxFor(x => x.Price, new { size = 4 }) 
      <a href="#" class="deleteRow">delete</a> 
     </p> 
    } 
</div> 

回答

2

由于您使用jquery动态生成HTML您必须使用事件代表团

而不是

$("a.deleteRow").on("click", function() { 
    $(this).parents("div.editorRow:first").remove(); 
    return false; 
}); 

尝试

$(document).on("click", "a.deleteRow" ,function() { 
    $(this).parents("div.editorRow:first").remove(); 
    return false; 
}); 

更多Here.

+0

伟大的...的解释和链接的感谢,现在很明显 – Willy 2014-09-30 06:03:54

+0

@Willy ...大。 。干杯..!!!! – 2014-09-30 06:04:20

2

更换

$("a.deleteRow").on("click", function() { 
$(this).parents("div.editorRow:first").remove(); 
return false; 
}); 

$(document).on("click","a.deleteRow", function() { 
$(this).parents("div.editorRow:first").remove(); 
return false; 
});