jQuery '.each' 并附加 '.click' 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18966222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:52:11  来源:igfitidea点击:

jQuery '.each' and attaching '.click' event

jqueryeach

提问by hcc

I am not a programer but I enjoy building prototypes. All of my experience comes from actionScript2.

我不是程序员,但我喜欢构建原型。我所有的经验都来自于 actionScript2。

Here is my question. To simplify my code I would like to figure out how to attach '.click' events to div's that are already existing in the HTML body.

这是我的问题。为了简化我的代码,我想弄清楚如何将“.click”事件附加到 HTML 正文中已经存在的 div。

<body>
<div id="dog-selected">dog</div>
<div id="cat-selected">cat</div>
<div id="mouse-selected">mouse</div>

<div class="dog"><img></div>
<div class="cat"><img></div>
<div class="mouse"><img></div>
</body>

My (failed) strategy was:
1) make an array of objects:

我的(失败的)策略是:
1)制作一个对象数组:

var props = {
"dog": "false",
"cat": "true",
"mouse": "false"
};  

2) iterate through the array with '.each' and augment each existing div with a '.click' event. Lastly, construct a local variable.

2) 使用 '.each' 遍历数组并使用 '.click' 事件扩充每个现有的 div。最后,构造一个局部变量。

here is a prototype:

这是一个原型:

$.each(props, function(key, value) {    
$('#'+key+'-selected').click(function(){
var key = value;  
});
});

回答by Neil.Allen

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

您可以使用的一种解决方案是为您希望单击事件处理程序绑定到的任何 div 分配一个更通用的类。

For example:

例如:

HTML:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

回答by Oriol

No need to use .each. clickalready binds to all divoccurrences.

无需使用.each. click已经绑定到所有div事件。

$('div').click(function(e) {
    ..    
});

See Demo

看演示

Note: use hard binding such as .clickto make sure dynamically loaded elements don't get bound.

注意:使用硬绑定.click来确保动态加载的元素不会被绑定。