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


当前回答

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;
});

其他回答

基于js的事件循环,点击clear按钮将在输入时触发搜索事件,因此下面的代码将正常工作:

input.onclick = function(e){
  this._cleared = true
  setTimeout(()=>{
    this._cleared = false
  })
}
input.onsearch = function(e){
  if(this._cleared) {
    console.log('clear button clicked!')
  }
}

上面的代码,点击事件预约了这个。_cleared = false事件循环,但该事件将始终在onsearch事件之后运行,因此您可以稳定地检查this。_cleared状态,以确定用户是否刚刚点击X按钮,然后触发onsearch事件。

这可以在几乎所有的条件下工作,粘贴文本,具有增量属性,ENTER/ESC键按下等。

我相信这是唯一的答案,只有当x被点击。

然而,这有点俗气,ggutenberg的答案对大多数人都适用。

$('#search-field').on('click', function(){
  $('#search-field').on('search', function(){
    if(!this.value){
      console.log("clicked x");
      // Put code you want to run on clear here
    }
  });
  setTimeout(function() {
    $('#search-field').off('search');
  }, 1);
});

其中“#search-field”是输入的jQuery选择器。使用'input[type=search]'选择所有搜索输入。通过在单击字段后立即检查搜索事件(Pauan的答案)来工作。

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
})` 

搜索或onclick工作…但我发现的问题是旧的浏览器——搜索失败。很多插件(jquery ui autocomplete或fancytree filter)都有模糊和聚焦处理程序。将其添加到自动完成输入框对我来说很有效。Value == ""因为它的计算速度更快)。当你点击小“x”时,模糊然后聚焦将光标保持在方框中。

PropertyChange和input在IE 10和IE 8以及其他浏览器上都可以工作:

$("#INPUTID").on("propertychange input", function(e) { 
    if (this.value == "") $(this).blur().focus(); 
});

对于FancyTree过滤器扩展,你可以使用一个重置按钮,并强制它的点击事件如下:

var TheFancyTree = $("#FancyTreeID").fancytree("getTree");

$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
    var n,
    leavesOnly = false,
    match = $(this).val();
    // check for the escape key or empty filter
    if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
        $("button#btnResetSearch").click();
        return;
    }

    n = SiteNavTree.filterNodes(function (node) {
        return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
        }, leavesOnly);

    $("button#btnResetSearch").attr("disabled", false);
    $("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();

// handle the reset and check for empty filter field... 
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
    if ($("input[name=FT_FilterINPUT]").val() != "")
        $("input[name=FT_FilterINPUT]").val("");
    $("span#SiteNavMatches").text("");
    SiteNavTree.clearFilter();
}).attr("disabled", true);

应该能够适应这为大多数用途。

我知道这是一个老问题,但我一直在寻找类似的东西。确定点击“X”以清除搜索框的时间。这里没有一个答案对我有帮助。其中一个很接近,但也受到影响,当用户点击“enter”按钮时,它会触发与点击“X”相同的结果。

我在另一个帖子上找到了这个答案,它非常适合我,只有当用户清空搜索框时才会触发。

$("input").bind("mouseup", function(e){
   var $input = $(this),
   oldValue = $input.val();

   if (oldValue == "") return;

   // When this event is fired after clicking on the clear button
   // the value is not cleared yet. We have to wait for it.
   setTimeout(function(){
     var newValue = $input.val();

      if (newValue == ""){
         // capture the clear
         $input.trigger("cleared");
      }
    }, 1);
});