使用FOR循环绑定事件序列 [英] Binding a sequence of events using the FOR loop

查看:81
本文介绍了使用FOR循环绑定事件序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上。我试图使用javascript jQuery库将一系列事件绑定到几个div。这就是我想要做的。

Hai. I am trying to bind a sequence of events to several divs using javascript jQuery library. Here is what I am trying to do.

屏幕上会有很多div,其中id为div1 div2 div3 ... div10,依此类推。然而,只有id为'div1'的第一个div将被隐藏所有其他div隐藏。当用户将鼠标悬停在div1上时,应该显示div2,当他将鼠标悬停在div 2上时,应该显示div 3,这应该会持续到最后一个div。

There will be many div's on the screen with id's div1 div2 div3 ... div10 and so on. However only the first div with id 'div1' will be dispalyed with all the other div's hidden. When the user hovers over div1, div2 should be shown and when he hovers over div 2, div 3 should be shown and this should continue sequently till the last div.

I av设法使用jQueries下一个方法提出解决方案。

I av managed to come up with a solution using jQueries next method.

$('div').each(function(){
    $(this).mouseover(function(){
        $(this).next().show();
    });
});

然而,因为我新学习javascript,我想用FOR循环重做它,它不会工作。

However since i am newly learning javascript i wanted to redo it using a FOR loop and it wont work.

for (var i=1; i<11; i++){
    $('#div' + i).mouseover(function(){
        $('#div' + (i+1)).show();
    });
}

经过一段时间的游戏后,我想,因为我正在创造一个新的函数'i'的值仅在函数执行时解释,而不是在创建函数时解释。有人可以向我解释如何避免这种陷阱,并使用javascripts FOR循环实现jQuery.next()的功能。谢谢。

After a bit of playing around, i figured that since i am creating a new function the value of 'i' gets interpreted only when the function is being executed and not when the function is being created. Can someone please explain to me how to avoid this pit fall and achieve what i av done with the jQuery.next() using javascripts FOR loop. Thanks.

推荐答案

问题是只有一个变量 i for所有div,它在for循环结束时的值将是11.你可以做的是像

The problem is that there only one variable i for all divs, and its value at the end on the for loop will be 11. What you can do is something like

for (var i=1; i<11; i++){
    $('#div' + i).mouseover(function(){
        var index_string = $(this).attr('id').substring(3), //return, say the string '6'
            index = parseInt(index_string, 10); //convert it to a number
        $('#div' + (index+1)).show();
    });
}

一种更复杂的方法,使用匿名函数存储索引:

A more sophisticated approach, using anonymous functions to store the indices:

for (var i=1; i<11; i++){
    (function() {
        var j = i;
        $('#div' + j).mouseover(function(){
            $('#div' + (j+1)).show();
        });
    })();
}

这篇关于使用FOR循环绑定事件序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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