Combine hover and click functions (jQuery)?

后端 未结 8 781
一整个雨季
一整个雨季 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
    });
    

提交回复
热议问题