jQuery'.each'和附加'.click'事件 [英] jQuery '.each' and attaching '.click' event

查看:302
本文介绍了jQuery'.each'和附加'.click'事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

<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>

我的(失败的)策略是:

1)创建对象数组:

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

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

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

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

这是一个原型:

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


推荐答案

您可以使用的一种解决方案是分配一个更通用的

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

例如:

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:

$( ".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'); 
    });
});

这篇关于jQuery'.each'和附加'.click'事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆