在while循环中将变量传递给:eq jquery选择器 [英] Passing variable to :eq jquery selector in a while loop
本文介绍了在while循环中将变量传递给:eq jquery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码将jquery hover
函数分配给<ul>
列表内的所有元素:
I'm trying to assign jquery hover
functions to all the elements inside <ul>
list with this code:
var element = 0;
var length = $(".artist-list-link").length;
while (element<length) {
$(".artist-list-link:eq("+element+")").hover(function() {
$(".artist-back:eq("+element+")").css('display','block');
$(".artist-hover:eq("+element+")").fadeIn(100);
}, function() {
$(".artist-back:eq("+element+")").css('display','none');
$(".artist-hover:eq("+element+")").fadeOut(100);
});
element++;
};
标记看起来像这样:
<ul>
<li><a class="artist-list-link" href="">Artist 1</a></li>
<li><a class="artist-list-link" href="">Artist 2</a></li>
<li><a class="artist-list-link" href="">Artist 3</a></li>
<li><a class="artist-list-link" href="">Artist 4</a></li>
<li><a class="artist-list-link" href="">Artist 5</a></li>
</ul>
我也为每个艺术家提供了一些div(我删除了所有链接,只是为了使其更具可读性.
And also I have some divs for each artist (I've removed all the links, just to make it more readable.
<div class="artist-thumbnail artist-size">
<div class="artist-card artist-size artist-hover"></div>
<div class="artist-card artist-size"><img src="" /></div>
<div class="artist-card artist-size artist-back">Artist 1</div>
</div>
但是上面的循环并没有真正起作用,尽管下面的代码可以完美地工作:
But the above loop doesn't really work, though code below works perfectly:
$('.artist-list-link:eq(0)').hover(function() {
$('.artist-back:eq(0)').css('display','block');
$('.artist-hover:eq(0)').fadeIn(100);
}, function() {
$('.artist-back:eq(0)').css('display','none');
$('.artist-hover:eq(0)').fadeOut(100);
});
可能是什么问题?感谢您的回答.
What could be the problem? Thanks for answers.
推荐答案
这是因为在调用回调时element
已更改.
That's because element
has changed when the callback is called.
您可以这样做:
while (element<length) {
(function(element) {
$(".artist-list-link:eq("+element+")").hover(function() {
$(".artist-back:eq("+element+")").css('display','block');
$(".artist-hover:eq("+element+")").fadeIn(100);
}, function() {
$(".artist-back:eq("+element+")").css('display','none');
$(".artist-hover:eq("+element+")").fadeOut(100);
});
})(element);
element++;
};
这可以在闭包中保护元素的值.
This protects your element's value in a closure.
这篇关于在while循环中将变量传递给:eq jquery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文