You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JavaScript的focusout事件仅触发一次?

解决focusout事件多次触发的问题

问题核心就是每次触发focusin时,都给textarea新增了一个focusout事件监听器,次数一多,失焦时自然会多次执行对应逻辑。这里给你几个简洁的解决办法:

方法1:使用once选项(最简洁)

给focusout的addEventListener添加第三个参数{once: true},这个监听器就只会执行一次,执行后自动销毁,不用手动处理:

document.getElementById('textarea').addEventListener('focusin', () => {
    document.getElementById('UserTextArea').classList.add('text-selected');
    document.getElementById('textarea').style.marginBottom = "0px";

    document.getElementById('textarea').addEventListener('focusout', () => {
        let CommentText = document.querySelector('.textarea').innerText;
        chrome.storage.local.set({SavedComments: CommentText}, function() {});
    }, { once: true }); // 新增此选项
});

方法2:将focusout监听器移到外部,只绑定一次

保存内容的逻辑不需要每次聚焦都重新绑定,直接把focusout监听器放在focusin外面,只初始化一次:

// 先绑定focusout,仅执行一次绑定
document.getElementById('textarea').addEventListener('focusout', () => {
    let CommentText = document.querySelector('.textarea').innerText;
    chrome.storage.local.set({SavedComments: CommentText}, function() {});
});

// 绑定focusin逻辑
document.getElementById('textarea').addEventListener('focusin', () => {
    document.getElementById('UserTextArea').classList.add('text-selected');
    document.getElementById('textarea').style.marginBottom = "0px";
});

方法3:手动移除监听器

如果必须在focusin内绑定,可以用命名函数,在focusout触发后手动移除监听器:

document.getElementById('textarea').addEventListener('focusin', () => {
    document.getElementById('UserTextArea').classList.add('text-selected');
    document.getElementById('textarea').style.marginBottom = "0px";

    function handleFocusOut() {
        let CommentText = document.querySelector('.textarea').innerText;
        chrome.storage.local.set({SavedComments: CommentText}, function() {});
        // 执行完移除监听器
        document.getElementById('textarea').removeEventListener('focusout', handleFocusOut);
    }

    document.getElementById('textarea').addEventListener('focusout', handleFocusOut);
});

内容的提问来源于stack exchange,提问作者king_anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:45:47