删除jQuery添加的按钮
Remove buttons added by jQuery
我正在使用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
});
相关文章:
- 将按钮添加到新元素中
- 使用加号按钮添加多个文本框,并通过PHP提交
- 复选框/单选按钮-添加所选项目的总价
- 将自定义按钮添加到现有网站
- 单击按钮添加HTML表单
- 将sharethis按钮添加到chrome扩展popup.html
- 从自定义DocuSign按钮添加信封自定义字段
- 我尝试将引导下拉按钮添加到 但下拉菜单不起作用.我该怎么做
- 将按钮添加到跨度
- 使用按钮添加到变量
- 单击禁用的按钮添加 CSS
- 将“下一步”和“上一个”按钮添加到较大的图像
- 将下一个和上一个按钮添加到我的图像滑块
- 按React按钮添加行
- 用jQuery点击按钮添加值
- 如何将下一个和上一个按钮添加到图像galary
- 如何为表行结果的每个按钮添加事件侦听器
- 使用setTimeout为按钮添加冷却时间
- 无法向按钮添加属性
- 如何将我的附加按钮添加到这个jQuery mp3播放器中