在jQuery中使用$(this)

sel*_*c82 2 jquery

当使用jQuery编写代码时,我发现自己使用var self = $(this)来引用我所在对象的当前上下文.例如:

$('#myDiv').click(function(e){

var self = $(this);

self.css('background', 'red');

});
Run Code Online (Sandbox Code Playgroud)

这很棒,但我必须为每个对象重复这个过程.例:

$('#myDiv').hover(function(){

//hover over function
var self = $(this);
self.css('background', 'red');

}, function(){

//hover out function
var self = $(this);
self.css('background', 'blue');

});
Run Code Online (Sandbox Code Playgroud)

我的问题是有没有办法我可以设置一个全局变量的自我,并用它来引用我所在的上下文.所以我想要全心全意地设置self = $(这个),无论我在哪里使用它都会自动引用我现在的目标是什么?

And*_*nza 6

您可以直接使用$(this).call()而不会出现问题