首页 > 关于jquery的this,$(this)可以作为变量保存吗?

关于jquery的this,$(this)可以作为变量保存吗?

遇到这么一个问题,如果把$(this)写在setTimeout里,就失效了,有什么办法可以提前保存$(this)吗?


下面用$(this)的地方直接用this_temp不就对了


你不是已经保存了么?this_temp


SetTimeout的function的this已经改变了,用箭头函数吧


可以使用 $.proxy(function, context) 来保持了特定的上下文(context )语境。修改后如下:

$(document).on('mousedown', '#piece', function(e){
    timeOut = setTimeout($.proxy(function(){
       $(this).detach(); 
    }, this), 1000);
});

$("body").on("click", function(){
    var timeout = setTimeout(function(){
        console.log($(this).attr("class"));
    }.call(this), 1000);
});

你不是已经保存到this_temp里了。用它就行了


你已经把$(this)存为this_temp了,下次直接用就可以了


可以啊,你已经定义了一个this_temp变量指向this ,你直接用this_temp就相当于在调用this了

【热门文章】
【热门文章】