简体   繁体   中英

How can I combine these jQuery .on() functions?

Here is my code. The swipes are for anywhere in the document, the click is for the close img, but they execute the same code. Any advice? It's not an overly big deal, but I would like smaller, cleaner code if I can. This is for a modal type window.

                 $(document).on("click", "#close", function () {
                     ttl.html(docTitle + air);
                     window.history.pushState({}, docTitle + air, docURL);
                 }).on("swipeleft swiperight", function () {
                     ttl.html(docTitle + air);
                     window.history.pushState({}, docTitle + air, docURL);
                 });

There's no ideal solution here, so you can simply do this:

var f = function () {
      ttl.html(docTitle + air);
      window.history.pushState({}, docTitle + air, docURL);
}
$(document).on("click", "#close", f).on("swipeleft swiperight", f);

If you do this in the global scope or in a big one, you may enclose the whole in an IIFE to keep the outer scope cleaner :

(function(){
    var f = function () {
          ttl.html(docTitle + air);
          window.history.pushState({}, docTitle + air, docURL);
    }
    $(document).on("click", "#close", f).on("swipeleft swiperight", f);
})();

You can create a function that does that and just call it.

function foo(ttl, docTitle, air, docURL) {
   ttl.html(docTitle + air);
   window.history.pushState({}, docTitle + air, docURL);
}

And just call it from within the on statements.

$(document).on("click", "#close", 
        foo(ttl, docTitle, air, docUrl)).
    on("swipeleft swiperight", 
        foo(ttl, docTitle, air, docUrl));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM