首页 > 解决方案 > 来自多个位置的 jQuery $('element').one() 事件调用

问题描述

我有一些模态在第二次打开时有奇怪的行为,它从我没想到的位置调用 .one() 事件。

当第一次点击.modal-trigger一切正常时,与点击相同.close-modal, .modal-sandbox。但是当我.modal-trigger再次点击时,jQuery 调用回调来自modalBox.one('animationend transitionend');

$(".modal-trigger").on('click', function (e) {
    e.preventDefault();
    let modalWindow = $($(this).attr("href"));
    let modalBox = modalWindow.find('.modal-box');
    let sidebarWidth = $aside.width();

    $("body").css({"overflow-y": "hidden"}).addClass('blurred');

    if ($(window).width() >= 992) {
       modalBox.css({"margin-left": `${sidebarWidth}px`});
    }

    animateCSS(modalWindow, 'showing', function (element) {
        element.addClass('show').removeClass('showing');
        modalBox.addClass('show');
    });
});

 $(".close-modal, .modal-sandbox").on('click', function () {
    let modalWindow = $(this).closest('.modal');
    let modalBox = modalWindow.find('.modal-box');

    modalBox.one('animationend transitionend', function () {
        modalBox.removeAttr('style');
        modalWindow.removeClass('show');
        $("body").css({"overflow-y": "auto"}).removeClass('blurred');
    });

    modalBox.removeClass('show');
});

function animateCSS(element, animationName, callback) {
    element = $(element);
    element.addClass(animationName);

    function handleAnimationEnd() {
        element.removeClass(animationName);

        if (typeof callback === 'function') callback(element);
   }

    element.one('animationend transitionend', handleAnimationEnd);
}

标签: javascriptjqueryjquery-events

解决方案


如果您one()多次调用...它将在每次调用时运行一次。

添加侦听器,然后使用删除它off()

 modalBox.on('animationend transitionend', function () {
    modalBox.removeAttr('style');
    modalWindow.removeClass('show');
    $("body").css({"overflow-y": "auto"}).removeClass('blurred');
    // remove listener
    modalBox.off('animationend transitionend')

});

推荐阅读