为刚创建的li元素绑定不同的功能 [英] Bind different functions for just created li elements

查看:61
本文介绍了为刚创建的li元素绑定不同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建li元素:

<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
[...]
</ul>

li_id是一个返回li id(= 1,2,3 ...)的数组值

li_id is an array value which returns li id (=1,2,3...)

如何在这样的代码中将不同的功能绑定到每个li元素:

How can I bind different functions to every li element in code like this:

for (li_id in lids)
{
console.log(li_id);                         
$(li_id).bind('mouseover', function() {
console.log(li_id);
});
}

以上操作无效.如何正确编写?

The above doesn't work. How to write it properly?

使用live()而不是bind(),它显示lids数组的最后一个元素的ID,而不是1,2,3 ... [...],就像$声明...

With live() instead of bind() it shows the id of the last element of the lids array, not 1,2,3...[...], like the console.log() outside the $ statement...

推荐答案

http://www .mennovanslooten.nl/blog/post/62

循环内的JavaScript封闭-简单的实际示例

鉴于您的HTML,可以用两种方式编写代码.

Given your HTML, the code can be written in two ways.

使用 jQuery 1.4 Event.data 参数:

var lids = [1,2,3];
for (i in lids) {
    var li_id = lids[i];

    $('#' + li_id).bind('mouseover', { id: li_id }, function(ev) {
        console.log(ev.data.id);
    });
}

或者,使用匿名函数创建一个闭包:

Or, creating a closure with anonymous function:

var lids = [1,2,3];
for (i in lids) {
    var li_id = lids[i];

    // an anonymous function 
    (function (id) {
        $('#' + id).bind('mouseover', function() {
            console.log(id);
        });        
    })(li_id); // ...called every time with different id

}

在这种情况下,我更喜欢jQuery Event.data方式.

I prefer jQuery Event.data way in this instance.

这篇关于为刚创建的li元素绑定不同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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