我正在使用jQuery向表单添加额外的选择和文本字段。但是,我希望能够删除添加的文本字段使用删除按钮。
一旦添加了字段,jQuery似乎无法检测到它。
jQuery
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'contact-list-div-' + counter).attr("class", 'contact-list-div');
newTextBoxDiv.after().html('<select></select>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >' + '<button type="button" class="removeButton" id="removeButton-' + counter + '">Remove Button</button>');
newTextBoxDiv.appendTo("#contact-list");
counter++;
});
$(".removeButton").click(function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});HTML
<div id="contact-list">
<div class="contact-list-div" id="contact-list-div-1">
<select></select>
<input>
<button type='button' class='removeButton' id='removeButton-1'>Remove Button</button>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>发布于 2015-02-27 21:37:04
您需要使用event-delegation
$(document).on('click', '.removeButton',function() {
$(this).parents('.contact-list-div').remove();
});在单击 .removeButton 的事件侦听器被注册为之后,将内容附加到DOM侦听器。因此,当您将单击事件绑定到该元素时,该元素并不存在。
通过事件委派,您可以将事件列表器绑定到现有的父(在本例中为document,但也可以使用)。这将监听与.removeButton选择器匹配的后代的所有事件。
发布于 2015-02-27 21:38:23
$('#contact-list').on('click', '.removeButton', function() {
//Your code
});发布于 2015-02-27 21:37:51
这是因为您正在将事件绑定到尚不存在的元素。
使用jQuery委派在尚不存在的元素上启用处理程序:
$("body").on("click", ".removeButton", function() {
alert(this.id);
});https://stackoverflow.com/questions/28766342
复制相似问题