gpt4 book ai didi

javascript - 嵌套事件监听器如何在第一次调用时绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 01:41:38 25 4
gpt4 key购买 nike

我正在尝试将事件绑定(bind)到异步加载的类选择器。我正在使用 jQuery .on 事件监听器,因此它将异步工作。

但是,当我在事件监听器中绑定(bind)另一个事件时。这意味着我必须触发事件两次才能使函数运行。

button.on("touchend", tapHandler);

function tapHandler()
button.swipe( {
//Generic swipe handler for all directions
tap:function() {
banner.toggleClass("alt")
}
});
});

有没有办法在第一次调用时立即调用嵌套事件监听器?

这个jsfiddle清楚地表明了问题。使用触摸设备时,必须按两次按钮才能调用toggleClass。 jsfiddle (use touch device in dev-tools)

最佳答案

Is there a way to immediately invoke the nested eventlistener on the first invocation?

如果您的意思是“...添加时”而不是“...在第一次调用时”,那么是的,至少有两种方法:

  1. 定义一个命名函数,在处理程序中使用它,然后直接调用它:

    function tapHandler()  {
    function swipeHandler() {
    banner.toggleClass("alt")
    }
    button.swipe( {
    //Generic swipe handler for all directions
    tap: swipeHandler
    });
    swipeHandler();
    });

    这只调用swipeHandler一次,并且不会向其传递事件对象;看看它的作用,看起来不错。更彻底的版本可能会循环按钮(因为 jQuery 对象是集合)。

  2. 使用triggertriggerHandler :

    function tapHandler()  {
    button.swipe( {
    //Generic swipe handler for all directions
    tap: function() {
    banner.toggleClass("alt")
    }
    });
    button.triggerHandler("tap");
    });

关于javascript - 嵌套事件监听器如何在第一次调用时绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com