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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2432003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:17:47  来源:igfitidea点击:

Combine hover and click functions (jQuery)?

javascriptjqueryfunctionclickhover

提问by eozzy

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

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

click:

点击:

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

hover:

徘徊:

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

can they be combined into one function?

它们可以合并为一个功能吗?

Thanks!

谢谢!

回答by Emil Ivanov

Use basic programming composition: create a method and pass the same function to clickand hoveras a callback.

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

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


Second way: use bindon:

第二种方式:使用:bindon

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


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

回答by Vergilius

Use mouseoverinstead hover.

使用鼠标悬停代替悬停。

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

回答by Nick Craver

You can use .bind()or .live()whichever is appropriate, but no need to name the function:

您可以使用.bind().live()任何合适的,但无需命名函数:

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

or if you were doing this on lots of element (not much sense for an IE unless the element changes):

或者如果您在很多元素上执行此操作(除非元素更改,否则对 IE 没有多大意义):

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

Note, this will only bind the firsthover argument, the mouseoverevent, it won't hook anything to the mouseleaveevent.

请注意,这只会绑定第一个悬停参数,即mouseover事件,它不会将任何内容挂接到mouseleave事件。

回答by Nick Craver

$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});

回答by St.Woland

var hoverAndClick = function() {
    // Your actions here
} ;

$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;

回答by PatrikAkerstrand

You could also use bind:

您还可以使用bind

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

回答by Adeel

i think best approach is to make a commonmethod and call in hoverand clickevents.

我认为最好的方法是制定一个通用方法并调用悬停点击事件

回答by Suhani Mendapara

  $("#target").on({
        hover: function(){
           //do on mouse hover
        },  
        click: function(){
            //do on mouse click
        }  
    });