[英]jQuery Can not remove section after Cloned
我創建按鈕Add Section
克隆部分.clone
它工作正常...
主要點我不能繼續是Remove Section
此按鈕不起作用。 我想點擊Remove Section
它將刪除它自己的部分。
HTML
<div style="margin-bottom:25px;">
<button class="add_section btn btn-primary" type="button"><i class="fa fa-plus"></i> Add Section</button>
</div>
<div class="panel clone" id="primary">
<div class="panel-heading">
<span class="panel-title" id="secPanel">Section #Primary</span>
<button style="float:right;" class="rem_section btn btn-primary" type="button"><i class="fa fa-remove"></i>Remove Section</button>
</div>
<div class="panel-body admin-form">
<div class="form-horizontal">
<div class="form-group">
<label class="col-lg-2 control-label">Description</label>
<div class="col-lg-8">
<input id="secTitle" name="txt_sectitle[]" value="" type="text" class="form-control">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pastclone"></div>
JS
jQuery(document).ready(function() {
// Init jQuery Add Section
$('.add_section').on('click', function(){
var num = $('div.clone').length,
clone = $('#primary').clone().attr('id', num);
clone.find('#secPanel').html('Section #' + num);
clone.find('[type=text]').val('');
clone.find('.rem_section').attr('class', 'rem_section'+num+' btn btn-primary');
clone.insertBefore("#pastclone");
return false;
});
// Init jQuery Remove Section
$(".clone").on("click", ".rem_section", function(){
$(this).parent(".clone").remove();
return false;
});
});
我的JSFIDDLE
clone元素也是動態創建的,因此您需要將處理程序綁定到動態元素的祖先元素,該元素在事件注冊時存在
$(document).on("click", ".clone .rem_section", function(){
$(this).closest(".clone").remove();
return false;
});
此外,當您克隆時,不會添加rem_section
類。
clone.find('.rem_section').attr('class', 'rem_section rem_section'+num+' btn btn-primary');
演示: 小提琴
無法刪除,因為您通過增量值更改每個元素的屬性類名稱。 因為您將click事件附加到class
上,所以不需要增量值。
這個
clone.find('.rem_section').attr('class', 'rem_section'+num+' btn btn-primary');
應該
clone.find('.rem_section').attr('class', 'rem_section btn btn-primary');
而remove元素只能找到直接的parent
元素,如果使用closest
元素,可能會更好:
$(document).on("click", ".rem_section", function(){
$(this).closest(".clone").remove();
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.