jQuery functions not responding after append()(jQuery函数在append()之后没有响应)
问题描述
我正在创建一系列 div 框,让用户可以使用 jQuery 从每个框中添加/删除项目.我发现在一个盒子里添加一个新元素后,我绑定到那个元素的点击函数没有响应.我的代码大致如下:
I'm creating a series of div boxes that lets users add/remove items from each box with jQuery. I find that after I add a new element to a box, the click function I have bound to that element will not respond. Here's roughly what my code looks like:
$(".add").click(function() {
$("#targetbox").append("<span class='remove'>This element was added</span>");
});
$(".remove").click(function() {
alert("removing");
$(this).remove();
});
如果我用项目预先填充#targetbox,它们会响应点击功能.只有动态添加的项目不响应函数.
If I pre-populate #targetbox with items, they respond to the click function. It's only the items that are dynamically added that do not respond to the function.
推荐答案
将click方法直接添加到新添加的元素中
Add the click method directly to your newly appended element
$(".add").click(function() {
$("#targetbox").append("<span class='remove'>This element was added</span>")
.bind("click",function(e) {
alert("removing");
$(this).remove();
});
});
或者使用 .live()
方法在添加任何新的 .remove
元素后为您绑定点击事件
Or use the .live()
method that will bind the click event for you after appending any new .remove
elements
$(".add").click(function() {
$("#targetbox").append("<span class='remove'>This element was added</span>");
});
$(".remove").live("click", function() {
alert("removing");
$(this).remove();
});
这篇关于jQuery函数在append()之后没有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery函数在append()之后没有响应


基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01