javascript - 来自多个位置的 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);
}
解决方案
如果您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')
});
推荐阅读
- mysql - 将矩阵存储在 mysql 中以实现快速完整矩阵检索
- c++ - 如何将“void”形式的值分配给“char”形式的变量?
- next.js - 如何在下一个身份验证中解决“getUserByAccount 不是函数”?
- python - 使用标量或向量作为输入的函数的 Numpy 最佳实践是什么?
- c# - 如何根据 REST 定义类似操作的端点
- android - Google Play 商店开发者帐户活动日志会显示上传记录和关键更改吗?
- node.js - 如何在 Node 中管理对 Postgresql 的大量调用
- reactjs - 如何在打字稿中正确使用区分联合,因此当一个属性为真时,需要另外两个属性
- arrays - 为什么 AbstractArray 的子类型会导致 Julia 中的矩阵运算不精确?
- amazon-web-services - API 网关 SQS 响应以 UnknownOperationException 结束