在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?


当前回答

document.querySelectorAll('input[type=search]').forEach(function (input) {
   input.addEventListener('mouseup', function (e) {
                if (input.value.length > 0) {
                    setTimeout(function () {
                        if (input.value.length === 0) {
                            //do reset action here
                        }
                    }, 5);
                }
            });
}

ECMASCRIPT 2016

其他回答

这里有一种方法。你需要添加增量属性到你的html或它不会工作。

window.onload = function() { var tf = document.getElementById('textField'); var button = document.getElementById('b'); 按钮禁用 = 真; var onKeyChange = 函数 textChange() { 按钮禁用 = (tf.value === “”) ?真 : 假; } tf.addEventListener('keyup', onKeyChange); tf.addEventListener('search', onKeyChange); } <输入 id=“文本字段” 类型=“搜索” 占位符=“搜索” 增量=“增量”> <按钮 id=“b”>去!</button>

实际上,每当用户搜索或单击“x”时,都会触发一个“search”事件。这特别有用,因为它理解“增量”属性。

现在,话虽如此,我不确定你是否能说出点击“x”和搜索之间的区别,除非你使用“onclick”黑客。不管怎样,希望这对你有所帮助。

多托罗网络参考

试试这个,希望能帮到你

$("input[name=search-mini]").on("search", function() {
  //do something for search
});
const inputElement = document.getElementById("input");
let inputValue;
let isSearchCleared = false;
inputElement.addEventListener("input", function (event) {
    if (!event.target.value && inputValue) {
        //Search is cleared
        isSearchCleared = true;
    } else {
        isSearchCleared = false;
    }
    inputValue = event.target.value;
});

2022简单,易读,简短的解决方案

哇,这么简单的问题居然有这么复杂的答案。

只需在你的搜索输入中添加一个“输入”监听器,当用户在输入中键入某些内容或单击清除图标时,它就会捕捉到。

document.getElementById('searchInput').addEventListener('input', (e) => { console.log('Input value: “${e.currentTarget.value}”'); }) <输入 id=“搜索输入” 类型=“搜索” 占位符=“搜索” />

如果你不能使用ES6+,那么下面是转换后的代码:

document.getElementById('searchInput').addEventListener('input', function(e) { 
  // Yay! You make it in here when a user types or clicks the clear icon
})`