开发者

Passing $this in JavaScript

How would I rewrite this to use a common function, pretending that the common function would eventually have more than th开发者_高级运维e 1 line of code in it:

$('.insert').hover(function() {
    $(this).css('cursor','pointer');
});
$('.delete').hover(function() {
    $(this).css('cursor','pointer');
});


Or if you just want to avoid duplicating code

$('.insert,.delete').hover(function() {
    $(this).css('cursor','pointer');
});


Just pull your current code into a separate function:

var f = function() {
    $(this).css('cursor','pointer');
};

and:

$('.insert').hover(f);
$('.delete').hover(f);


this is just a variable, and like any variable you can pass it as a parameter to another function:

function my_func(obj) {
   $(obj).css('cursor','pointer');
}

$('.insert').hover(function() {
    my_func(this);
});
$('.delete').hover(function() {
    my_func(this);
});


If I understand correctly...

function(elem) {
   $(elem).hover(function() {
      $(this).css('cursor','pointer');
   });
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜