简体   繁体   中英

Scoping issues with Jquery slideToggle

I'm using slideToggle and wondering how to pass a variable to the callback function. It traces back undefined. Any ideas? Cheers!

$('.drop-box .button').click(function(){

    var target = $(this).parent();

    var myVar = $(this);    

    target.slideToggle(300, function(myVar){

        alert(myVar); // undefined
    });

    return false;
});

Remove myVar from the callback function's arguments. You don't need to pass in the variable, since it is already in scope.

target.slideToggle(300, function() {
    alert(myVar);
});

As the .slideToggle() doesn't pass any parameters in to the callback you'll have to remove the parameter myVar from your callback's definition. As the callback parameter was hiding your variable the original variable comes back in to scope.

$('.drop-box .button').click(function(){
    var target = $(this).parent();
    var myVar = "hello";    
    target.slideToggle(300, function(){
        alert(myVar); // hello
    });

    return false;
});

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