Combine hover and click functions (jQuery)?

我是研究僧i 提交于 2019-11-27 17:15:21
Emil Ivanov

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);

Second way: use bindon:

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

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

Use mouseover instead hover.

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

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

$('#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):

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

Note, this will only bind the first hover argument, the mouseover event, it won't hook anything to the mouseleave event.

$("#target").hover(function(){
  $(this).click();
}).click(function(){
  //common function
});
var hoverAndClick = function() {
    // Your actions here
} ;

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

You could also use bind:

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

i think best approach is to make a common method and call in hover and click events.

  $("#target").on({
        hover: function(){
           //do on mouse hover
        },  
        click: function(){
            //do on mouse click
        }  
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!