删除jQuery添加的按钮

Remove buttons added by jQuery

本文关键字:按钮 添加 jQuery 删除      更新时间:2023-09-26

我正在使用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'>
$('#contact-list').on('click', '.removeButton', function() {
    //Your code                        
});

您需要使用事件委派:

$(document).on('click', '.removeButton',function() {
    $(this).parents('.contact-list-div').remove();                     
});

在注册了用于单击.removeButton的事件侦听器之后,您可以将内容附加到DOM中。因此,在您将点击事件绑定到该元素时,该元素并不存在。

通过事件委派,您可以将事件列表绑定到现有父级(在本例中为document#contact-list也可以工作)。这将监听其子代与.removeButton-选择器匹配的所有事件。

演示

这是因为您将事件绑定到尚不存在的元素。

使用jQuery委派对尚未存在的元素启用处理程序:

$("body").on("click", ".removeButton", function() {
    alert(this.id); 
});

只在第一个按钮处添加click监听器
尝试使用委托:

$(document).delegate(".removeButton", "click", function() {
    alert(this.id);
});

这告诉文档,每当事件单击类为"removeButton"的元素时,它都应该调用该回调

(你可以在这里看到它的工作)

因为元素是用jQuery动态添加的,所以jQuery的正常.click事件将无法检测到新添加的元素。

请改用.on。参见以下示例:

$("body").on("click", ".removeButton", function() {
    alert(this.id); //this never shows, only on the element that was 
                    //added directly added using html, in this case removeButton-1
});