绑定JQuery中动态元素的click事件 [英] binding click event for dynamic element in JQuery
问题描述
我有一个div,它通过.html属性
I have a div which is filled dynamically after calling an AJAX call by .html attribute
$("#gallery").html(imagesHtml);
独立imagesHtml我现在有2个分别称为"prebtn"和"nxtbtn"的按钮,我正在尝试使用JQuery中的以下语法绑定这些按钮:
insdie imagesHtml i ahve 2 buttons called "prebtn" and "nxtbtn" now I'm trying to bind these buttons with the following syntax in JQuery:
$("#gallery").bind('click', '#nxtbtn', function() {
alert('next');
});
和
$("#gallery").bind('click', '#prebtn', function() {
alert('previous');
});
但是当我单击其中一个按钮时,两个事件都被触发,并且显示下一个"和上一个"的提示;但是,我只单击了其中一个按钮!
but whener I click on one of the buttons both events get triggered and it shows allert for "next" and "previous"; howevr I have click just one of the buttons!
如果需要更多说明,请告诉我.
Please let me know if you need more clarification.
谢谢
推荐答案
您正在混淆 bind
和 on
方法.它们看起来很相似,但是bind
的功能较少:它不支持事件委托.第二个参数不是委托事件的选择器,而是data
参数.
You're confusing the bind
and on
methods. They look similar, but bind
has less functionality: it does not support event delegation. The second argument is not the selector for the delegated events, but a data
argument.
这将起作用:
$("#gallery").on('click', '#nxtbtn', function() {
这篇关于绑定JQuery中动态元素的click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!