在 focus() 事件中调用时,alert() 函数正在循环
alert() function is looping when called in focus() event
我想要在关注输入时弹出警报。它会正确弹出,但是当我单击 'OK' 或 'x' 即取消时,它会无限循环并且永远不会关闭。
$('input').focus(function () {
alert('hello');
});
这是因为 input
在 alert
关闭时再次获得焦点(这是出现时的新焦点 - 请注意对话框中按钮周围的轮廓?)
如果你只想让警报显示一次,你也许可以写类似这样的东西:
let hasShownAlert = false
$('input').focus(function () {
if (!hasShownAlert) {
hasShownAlert = true
alert('hello')
}
})
当然,您可以使用状态容器或其他方式改进它,但这是实现它的最简单方法。 (注意:hasShownAlert
变量必须在 onfocus
处理程序之外定义,否则它将被垃圾收集器清除。)
更新:因此,如果您不希望它只显示一次,您可以采取一些措施。第一个,更简单,将监听 click
事件,而不是焦点。第二种方法是设置一个 didShowAlert
变量——每次触发处理程序时反转值。例如...
let didShowAlert = false
$('input').on('focus', (ev) => {
if (didShowAlert) {
didShowAlert = false
} else {
didShowAlert = true
alert('hello')
}
})
你可以试试
$(document).on("focus", 'input:not(.unFocus)', function() {
alert('hello');
$('input').addClass('unFocus');
setTimeout(function() {
$('input').removeClass('unFocus');
}, 10);
});
这可能不是理想的方法,但它确实有效:)
我想要在关注输入时弹出警报。它会正确弹出,但是当我单击 'OK' 或 'x' 即取消时,它会无限循环并且永远不会关闭。
$('input').focus(function () {
alert('hello');
});
这是因为 input
在 alert
关闭时再次获得焦点(这是出现时的新焦点 - 请注意对话框中按钮周围的轮廓?)
如果你只想让警报显示一次,你也许可以写类似这样的东西:
let hasShownAlert = false
$('input').focus(function () {
if (!hasShownAlert) {
hasShownAlert = true
alert('hello')
}
})
当然,您可以使用状态容器或其他方式改进它,但这是实现它的最简单方法。 (注意:hasShownAlert
变量必须在 onfocus
处理程序之外定义,否则它将被垃圾收集器清除。)
更新:因此,如果您不希望它只显示一次,您可以采取一些措施。第一个,更简单,将监听 click
事件,而不是焦点。第二种方法是设置一个 didShowAlert
变量——每次触发处理程序时反转值。例如...
let didShowAlert = false
$('input').on('focus', (ev) => {
if (didShowAlert) {
didShowAlert = false
} else {
didShowAlert = true
alert('hello')
}
})
你可以试试
$(document).on("focus", 'input:not(.unFocus)', function() {
alert('hello');
$('input').addClass('unFocus');
setTimeout(function() {
$('input').removeClass('unFocus');
}, 10);
});
这可能不是理想的方法,但它确实有效:)