简体   繁体   中英

jQuery undefined variable in IE8

I've created a jQuery mini script for slider. It's work perfectly in Firefox, Chrome, IE9 but when I hover in IE7, IE8. It's show an alert error (Undefined current_hover_item).

$('.nav-item').hover(function(){
        var current_hover_item = $(this).children().attr('rel');
        $('.show-item').hide();
        $(current_hover_item).fadeIn(1000);
        $(this).animate({"width": "+=10px", opacity: 0.6}, 500, function(){
             $(this).animate({"width": "-=10px", opacity: 1}, 500);
        });
}, function(){
        $(current_hover_item).fadeOut(1000);
        return false;
});

I tried remove (var) keywords but when I'm hover, it won't show everything. Please help me. Thanks.

current_hover_item is undefined in the second function, since the definition in the first function is in a closure .

You need to declare current_hover_item in both functions. Or, since you only use the variable once in each function, remove it entirely, like this:

$('.nav-item').hover(function(){
        $('.show-item').hide();
        $($(this).children().attr('rel')).fadeIn(1000);
        $(this).animate({"width": "+=10px", opacity: 0.6}, 500, function(){
             $(this).animate({"width": "-=10px", opacity: 1}, 500);
        });
}, function(){
        $($(this).children().attr('rel')).fadeOut(1000);
        return false;
});

Or preferably refactor your code.

I was having this problem earlier today. I fixed it by declaring the variable outside of any jquery functions (including .ready()) and then set it where you need it (where you are currently declaring it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM