结合悬停和单击功能(jQuery)?

2022-01-22 00:00:00 function hover jquery click javascript

可以将悬停和点击功能合二为一,例如:

Can hover and click functions be combined into one, so for example:

点击:

$('#target').click(function() {
  // common operation
});

悬停:

$('#target').hover(function () {
    // common operation
});

它们可以组合成一个功能吗?

can they be combined into one function?

谢谢!

推荐答案

使用基本的编程组合:创建一个方法并将相同的函数传递给 clickhover 作为回调.

Use basic programming composition: create a method and pass the same function to click and hover as a callback.

var hoverOrClick = function () {
    // do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);

<小时>

第二种方式:使用bindon:

$('#target').on('click mouseover', function () {
    // Do something for both
});

<小时>

jQuery('#target').bind('click mouseover', function () {
    // Do something for both
});

相关文章