[英]Get single event on click on div in for loop
var id=100;
for(var i=0;i<5;i++) {
$("#divtext_"+id).click(function(e) {
onClicked();
});
}
function onClicked() {
alert("Clicked")
}
.on()
, delegate()
, and one()
events. .on()
, delegate()
和one()
事件。 onClicked()
function gave an alert()
4 times. onClicked()
函数发出4次alert()
。 This is how I would expect the code to run under jquery, the options here would be to either use .unbind ( http://api.jquery.com/unbind/ ) to remove all previous instructions for this div or to check if the event has already been bound, this has been covered here. 这就是我希望代码在jquery下运行的方式,这里的选项是使用.unbind( http://api.jquery.com/unbind/ )删除此div的所有先前说明,或者检查是否事件已经绑定,此处已涉及。 How to check if click event is already bound - JQuery
如何检查click事件是否已绑定-JQuery
Presuming you have divs with IDs divtext_0
... divtext_4
假设您有ID为
divtext_0
... divtext_4
div
for(var i=0;i<5;i++) {
$("#divtext_"+i).click(function(e) {
onClicked();
});
}
function onClicked() {
alert("Clicked")
}
At the moment you are adding multiple click handlers to the div divtext_100
- rather than adding one click handler to multiple divs. 目前,您要向div
divtext_100
添加多个单击处理程序-而不是向多个div添加一个单击处理程序。
It is hard to say what is best without seeing your HTML - but if you gave all your divs a class, eg 'clickable', then you can avoid any loops and make any div with that class clickable. 在看不到HTML的情况下很难说出什么是最好的-但是,如果给所有div一个类,例如“ clickable”,则可以避免任何循环并使该类的任何div可单击。
<div class="clickable"></dvi>
You could simply do. 你可以做。
$(".clickable").click(function(e) {
onClicked();
});
function onClicked() {
alert("Clicked")
}
try this: 尝试这个:
$("#divtext_"+id).one("click", function(e){
onClicked();
});
You can use $("#divtext_"+id).off('click',onClicked).on('click',onClicked); 您可以使用$(“#divtext _” + id).off('click',onClicked).on('click',onClicked);
function onClicked() {
alert("Clicked")
}
'.off' prevents binding of onClicked function multiple times. '.off'防止多次绑定onClicked函数。 I think using
.off
will solve your problem. 我认为使用
.off
将解决您的问题。 If you are using older version of jquery then use .unbind
. 如果您正在使用旧版本的jquery,请使用
.unbind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.