开发者

jQuery - why $(this) doen't work in child scopes?

I can't figure out why this script won't work unless i create a reference to $(this) and assign it to another variable like $_this =开发者_高级运维 $(this); this was the only solution i got, but was wondering if there is a better one - a less newbie one. Observe that i want to be able to use it in the $_this.prepend("Choose"+res) part, after the get response in a callback function:

 $('#loadScript').one('click',function(e){
    $loading = $('<span> Loading Files... </span>');
    $(this).after($loading);
    $_this = $(this);

    $.get('eval.php',{loadScriptGetOptions:1}, function(res){
     setTimeout(function(){
      $loading.remove();
      $_this.prepend("<option>Choose</option>"+res);
     },1200)

    })

})

thanks in advance.


You forgot the use of var in two places:

$loading = ...

and

$_this = ...

And I like self vs the ugly underscore there.

 $('#loadScript').one('click',function(e){

    var $loading = $('<span> Loading Files... </span>');
    $(this).after($loading);

    var $self = $(this);

    $.get('eval.php',{loadScriptGetOptions:1}, function(res){
      setTimeout(function(){
         $loading.remove();
         $self.prepend("<option>Choose</option>"+res);
      }, 1200);

    });

});


Your $_this.prepend is getting called in a setTimeout function, where this is different then in the outer functions. You could have done something like:

function myFunc() {
    // What is $(this) here? 
}

 $('#loadScript').one('click',function(e){
    $loading = $('<span> Loading Files... </span>');
    $(this).after($loading);
    $_this = $(this);

    $.get('eval.php',{loadScriptGetOptions:1}, function(res){
       setTimeout(myFunc, 1200);
    })
})

Otherwise, I think your solution seems OK.

Note that $_this is a closure variable as used by function you use in setTimeout, so if you need to reference a known element, you can and should get rid of it as others commented (i.e. use $('#loadScript') to access the element directly).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜