使用FOR循环绑定事件序列

编程入门 行业动态 更新时间:2024-10-18 12:29:05
本文介绍了使用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循环绑定事件序列

本文发布于:2023-11-27 21:56:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   序列   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!