如何向在 jquery 中动态创建的元素添加操作?
我有一个按钮,当您单击此按钮时,它会动态创建第二个按钮。我需要在动态创建的按钮(第二个按钮)上放置一个单击事件,我这样做了,但我的单击功能不起作用。
如何让我的点击函数与动态创建的元素一起使用?
I have a button, when you click this button it dynamically creates a second button. I need to place a click event on to the dynamically created button (second button), which I do, but my click function isn't working.
How can I get my click function to work with dynamically created elements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要在创建第二个按钮后将单击事件绑定到它。或者使用 jQuery Live 或 Delegate 函数。
http://api.jquery.com/delegate/
如果您需要更多帮助,请发布一些代码。
You either need to bind the click event to the second button after it's created. Or use the jQuery Live or Delegate functions.
http://api.jquery.com/delegate/
Post some code if you need any more help.
我知道这个问题很久以前就被问过......
从 jQuery v1.7 开始,正确的方法是:
参考:http://api.jquery.com/on /
I know this question was asked a long while ago...
Since jQuery v1.7 the correct way to do that is :
Ref : http://api.jquery.com/on/
您必须使用 jQuery
.live()
函数,可以在此处。例子:
You have to use the jQuery
.live()
function which can be found here.Example:
这是一个示例。
标记:
脚本:
Here is an example.
Markup:
Script:
查看 jQuery .live()
jQeru .live()
check out jQuery .live()
jQeru .live()
您需要使用 jqueries live 方法附加一个事件。它将事件绑定到当前和未来元素的所有实例。
这样,单击事件就会添加到类名为 classname 的所有元素中 - 即使您插入更多具有相同类的元素。
you need to attach an event using jqueries live method. It will bind the event to all instances of current and future elements.
this way the click event is added to all elements with the classname of classname - even if you insert more elements with the same class.