Combine hover and click functions (jQuery)?

后端 未结 8 739
一整个雨季
一整个雨季 2020-12-04 08:50

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

click:

$(\'#target\').click(function() {
  // common operation
});
相关标签:
8条回答
  • 2020-12-04 09:31

    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
    });
    
    0 讨论(0)
  • 2020-12-04 09:33
      $("#target").on({
            hover: function(){
               //do on mouse hover
            },  
            click: function(){
                //do on mouse click
            }  
        });
    
    0 讨论(0)
  • 2020-12-04 09:36

    You could also use bind:

    $('#myelement').bind('click hover', function yourCommonHandler (e) {
       // Your handler here
    });
    
    0 讨论(0)
  • 2020-12-04 09:38

    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.

    0 讨论(0)
  • 2020-12-04 09:40

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

    0 讨论(0)
  • 2020-12-04 09:43

    Use mouseover instead hover.

    $('#target').on('click mouseover', function () {
        // Do something for both
    });
    
    0 讨论(0)
提交回复
热议问题