javascript - jQuery $ ('element' ).one() 来自多个位置的事件调用

标签 javascript jquery jquery-events

我有一些模态在第二次打开时有奇怪的行为,它从我没有预料到的位置调用 .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);
}

最佳答案

如果您多次调用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')

});

关于javascript - jQuery $ ('element' ).one() 来自多个位置的事件调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044277/

相关文章:

jquery - jqplot:如何不渲染任何x轴标签

javascript - 在 jQuery 中检测单个按键事件上的多个键

javascript - 为什么在这个html/css/jquery中注册了两个点击事件

javascript - jquery ajax 成功 php while

javascript - 即使使用单引号,ng-include 也不起作用

javascript - setState() 导致 props 未定义

javascript - Webpack 在 bundle.js 中包含未使用的库

javascript - jquery Accordion 在部分 ajax 页面重新加载后损坏

javascript - Jquery/Ajax/JavaScript 时间倒计时不停

javascript - 如何在触发 'submit'事件之前触发 'blur'事件?