开发者

Combine hover and click functions (jQuery)?

开发者 https://www.devze.com 2022-12-22 22:18 出处:网络
Can hover and click functions be combined into one, so for example: click: $(\'#tar开发者_高级运维get\').click(function() {

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

click:

$('#tar开发者_高级运维get').click(function() {
  // common operation
});

hover:

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

can they be combined into one function?

Thanks!


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


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


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.


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

精彩评论

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