在JavaScript中传递$ this

Phi*_*enn 1 javascript jquery

我如何重写它以使用一个通用函数,假装公共函数最终将包含超过1行代码:

$('.insert').hover(function() {
    $(this).css('cursor','pointer');
});
$('.delete').hover(function() {
    $(this).css('cursor','pointer');
});
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 6

或者,如果您只是想避免重复代码

$('.insert,.delete').hover(function() {
    $(this).css('cursor','pointer');
});
Run Code Online (Sandbox Code Playgroud)


cas*_*nca 5

只需将当前代码拉入单独的函数:

var f = function() {
    $(this).css('cursor','pointer');
};
Run Code Online (Sandbox Code Playgroud)

和:

$('.insert').hover(f);
$('.delete').hover(f);
Run Code Online (Sandbox Code Playgroud)