简体   繁体   English

如何合并这些jQuery .on()函数?

[英]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. 滑动适用于文档中的任何位置,单击适用于关闭的img,但它们执行相同的代码。 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 : 如果在全局范围内或在较大范围内执行此操作,则可以将整个范围包含在IIFE中,以使外部范围更干净:

(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. 只需从on语句中调用它即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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