简体   繁体   English

jQuery绑定dblclick事件到多个元素

[英]jquery bind dblclick event to multiple elements

I am attempting to bind a dblclick event to divs in a nodeList which I am iterating through. 我正在尝试将dblclick事件绑定到要迭代的nodeList中的div。 Here is the code: 这是代码:

var elems = document.getElementsByClassName("click");
currentLocation = elems[0].id;
for (var i=0; i<elems.length; i++){
    $(elems[i]).dblclick(function() {
            if((elems[i].id) != currentLocation){
                badAnswer = true;
                alert(badAnswer);
            }
        });

    }

currentLocation is a global variable set to the first element id of the node list. currentLocation是设置为节点列表的第一个元素ID的全局变量。 badAnswer is also a global boolean set to false. badAnswer还是设置为false的全局布尔值。 If a element is double clicked that matches an element other than the currentLocation global, badAnswer is set to true. 如果双击与currentLocation全局以外的其他元素匹配的元素,则badAnswer设置为true。

Currently I receive a undefined error, which I tried to remedy by creating a local variable inside of the event handler. 当前,我收到一个未定义的错误,我试图通过在事件处理程序内部创建局部变量来纠正该错误。 This didn't seem to work either and badAnswer is always true on double click as the elementID is always equal to the ID value of the last element. 这似乎也不起作用,并且双击时badAnswer始终为true,因为elementID始终等于最后一个元素的ID值。

Is there a better way to do this? 有一个更好的方法吗?

Yes, there is a much better way: 是的,还有更好的方法:

var currentLocation = $(".click")[0].id;
$(".click").on("dblclick", function() {
    if (this.id != currentLocation) {
        badAnswer = true;
    }
});
$('.click').dblClick(function() {
    if(this.id != currentLocation) {
        ...
    }
});

You're already using jQuery so you might as well use the selectors...much easier! 您已经在使用jQuery,因此不妨使用选择器...要容易得多!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM