开发者

Assigning a variable to a wrapper set in jQuery doesn't make the code work

开发者 https://www.devze.com 2023-04-09 18:45 出处:网络
I am trying to cache or to assign my selector $(\'#img-grp-wrap .img-wrap img:first-child\') to a variable because I used it a lot of times in the code and I kept on repeating myself. But for some rea

I am trying to cache or to assign my selector $('#img-grp-wrap .img-wrap img:first-child') to a variable because I used it a lot of times in the code and I kept on repeating myself. But for some reason, when I assigned my selection to a variable, the code doesn't work anymore. Please see bel开发者_Go百科ow (1st one is working, 2nd one not working):

Non-cached (working):

http://jsfiddle.net/g5tvZ/

Cached (not working):

http://jsfiddle.net/uMe2p/

(The code is supposed to automatically slide through the images and be able to use next/prev buttons to navigate. Please ignore the extra var rotate; on top. I would also appreciate any other refactoring tips about the code.)


This:

var imgFirst = $('#img-grp-wrap .img-wrap img:first-child');

leaves a set of DOM elements (along with jQuery wrapping) in imgFirst. Your imgFirst will match the state of the DOM when you assign your value to imgFirst.

Then later you change the DOM so :first-child doesn't select the same element that it used to and you're left with the wrong thing in imgFirst. Basically, the DOM changes but your imgFirst doesn't track those changes.


I'd like to point out another issue you have with your code. You need to remove the var from in front of the rotate assignment here so that you are assigning to the same global variable that keeps track of your timer. With the var in front of it, it's a local variable and you will get multiple timers stacking up when you repeatedly click on the prev or next buttons (which it's possible to make happen). So change this:

$('#img-grp-wrap .prev, #img-grp-wrap .next').hover(function() {
    clearInterval(rotate);
}, function() {
   var rotate = setInterval(function() {
        slideShow();
    }, 4000);
});

to this:

$('#img-grp-wrap .prev, #img-grp-wrap .next').hover(function() {
    clearInterval(rotate);
}, function() {
    rotate = setInterval(function() {
        slideShow();
    }, 4000);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号