Passing variable to :eq jquery selector in a while loop

坚强是说给别人听的谎言 提交于 2021-01-28 19:42:47

问题


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++;
};

The markup looks like this:

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

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.


回答1:


That's because element has changed when the callback is called.

You can do this :

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.



来源:https://stackoverflow.com/questions/13975902/passing-variable-to-eq-jquery-selector-in-a-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!