2014-09-30 79 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; 
}); 
相關問題