gpt4 book ai didi

javascript - 禁用/启用事件监听器

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

我想在元素聚焦时禁用事件监听器,并在元素聚焦时重新启用事件监听器。我怎样才能做到这一点?

*//event listener execute function on paste*
document.addEventListener('paste', function (evt) {
pasteClipboardURL(evt);
});

*//on focus disable event listener paste event and function*
$('#input-url').on('focus', function (url) {
*//disable document.addEventListener('paste', function (evt)*
});

$('#input-url').on('focusout', function (url) {
*//enable document.addEventListener('paste', function (evt)*
});

最佳答案

我不想动态添加/删除监听器,而是更愿意设置一个在焦点或焦点离开时切换的标志,并在主监听器中检查该标志:

let focused = false;
$(document).on('paste', (e) => {
if (!focused) pasteClipboardURL(e);
});
$('#input-url')
.on('focus', () => focused = true)
.on('focusout', () => focused = false);

const pasteClipboardURL = () => console.log('pasteClipboardURL');
let focused = false;
$(document).on('paste', (e) => {
if (!focused) pasteClipboardURL(e);
});
$('#input-url')
.on('focus', () => focused = true)
.on('focusout', () => focused = false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="some other input">
<input id="input-url" placeholder="input-url">
<input placeholder="some other input">

您还可以监听输入上的 paste 事件,并对该事件使用 stopPropagation,以便文档监听器看不到它:

const pasteClipboardURL = () => console.log('pasteClipboardURL');
$(document).on('paste', pasteClipboardURL);
$('#input-url').on('paste', e => e.stopPropagation());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="some other input">
<input id="input-url" placeholder="input-url">
<input placeholder="some other input">

关于javascript - 禁用/启用事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60747142/

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