最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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', function (e) {
    // Long and fancy code
});

jQuery(window).resize(function () {
    // Do the same fancy stuff (identical code)
});

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', function (e) {
    // Long and fancy code
});

jQuery(window).resize(function () {
    // Do the same fancy stuff (identical code)
});
Share Improve this question edited Dec 23, 2015 at 13:20 Nikita 웃 asked Dec 23, 2015 at 9:04 Nikita 웃Nikita 웃 2,0601 gold badge23 silver badges45 bronze badges 1
  • 2 Also keep in mind that the resize function might slow down your client's brwoser / make resizing laggy laggy, see this reference on how to prevent that. – Clemens Himmer Commented Dec 23, 2015 at 9:18
Add a comment  | 

4 Answers 4

Reset to default 15

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.

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

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

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)

  1. 暂无评论