如何使文本输入框的keyup函数仅在输入字符时触发,排除聚焦操作?
解决方案
你可以通过以下几种方式实现仅在用户实际输入(修改内容)时触发函数:
方法一:对比输入内容变化
在事件触发时,对比当前输入值和上一次的记录值,只有当值发生改变时才执行逻辑,同时更新记录值:
$(document).ready(function () { let lastInputValue = $("#searchInput").val(); // 初始化记录输入框初始值 $("#searchInput").keyup(function () { const currentValue = $(this).val(); if (currentValue !== lastInputValue) { // 仅内容变化时执行操作 $("#autoSearchButton a").attr("href", currentValue); lastInputValue = currentValue; // 更新记录的旧值 } }); });
方法二:使用input事件替代keyup
input事件是专门监听输入框内容变化的事件,键盘输入、粘贴、拖拽修改内容等操作都会触发它,而单纯聚焦输入框但不修改内容的操作不会触发,是更简洁适配的方案:
$(document).ready(function () { $("#searchInput").on('input', function () { const inputString = $(this).val(); $("#autoSearchButton a").attr("href", inputString); }); });
方法三:过滤非内容修改按键
通过判断事件对象的key值,只处理会改变输入内容的按键(比如字母、数字、退格、删除等),但这种方式需要覆盖较多按键场景,通用性稍弱:
$(document).ready(function () { $("#searchInput").keyup(function (event) { // 定义会修改输入内容的按键集合 const editableKeys = ['Backspace', 'Delete', ' ', ...Array.from({length:26},(_,i)=>String.fromCharCode(65+i)), ...Array.from({length:10},(_,i)=>String(i))]; if (editableKeys.includes(event.key)) { const inputString = $(this).val(); $("#autoSearchButton a").attr("href", inputString); } }); });
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

