Combining $('body').on('click') with $(window).resize(function() in jQuery

后端 未结 4 414
旧巷少年郎
旧巷少年郎 2021-01-12 08:01

Wondering if there is a way to combine identical code of 2 separate functions into 1 function.

In my case:

jQuery(\'body\').on(\'click\', \'.some_div         


        
相关标签:
4条回答
  • 2021-01-12 08:40

    You can define a single function which you call under both events:

    function doSomething(e) {
        console.log('Your code here...');
    }
    
    jQuery('body').on('click', '.some_div', doSomething);
    jQuery(window).resize(doSomething);
    

    Bear in mind that the reference to this will be different depending on the event raised, should that be used within your doSomething function.

    0 讨论(0)
  • 2021-01-12 08:52

    create a separate function and call it from required locations:

    jQuery('body').on('click', '.some_div', function(e){
        myFunction();
    });
    
    
    jQuery(window).resize(function() {
        myFunction();
    });
    
    function myFunction(){
       // Long and fancy code
    }
    
    0 讨论(0)
  • 2021-01-12 08:57

    There's another way to do that.

    jQuery('body').on('click', '.some_div', function (e) {
        // Long and fancy code
    });
    
    jQuery(window).resize(function () {
        $('.some_div').trigger('click')
    });
    
    0 讨论(0)
  • 2021-01-12 08:58

    You can create a function to handler both the events and pass this function reference to the event handlers.

    function myHandler(e) {
        // Long and fancy code
    }
    
    jQuery('body').on('click', '.some_div', myHandler);
    
    jQuery(window).resize(myHandler);
    
    0 讨论(0)
提交回复
热议问题