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


当前回答

搜索或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);

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

其他回答

我还不如把我的5c也加进去。

keyup事件不检测鼠标单击X以清除字段,但输入事件检测击键和鼠标单击。您可以通过检查事件的originalEvent属性来区分触发输入事件的事件—它们之间有相当多的区别。

我发现最简单的方法如下:

jQuery("#searchinput").on("input",function(event) {
      var isclick = event.originalEvent.inputType == undefined;
   }   

通过击键,event.originalEvent.inputType = "insertText"。

我使用Chrome -没有在其他浏览器中测试,但鉴于事件对象是相当普遍的,我猜这将在大多数情况下工作。

注意,仅仅单击输入不会触发事件。

在我的情况下,我不想使用JQuery和我的输入也是通用的,所以在某些情况下,它可以是类型“搜索”,但并不总是这样。我可以让它稍微延迟一点基于这里的另一个答案。基本上,我想在单击输入时打开一个组件,而不是在单击clear按钮时打开。

function onClick(e: React.MouseEvent<HTMLInputElement>) {
  const target = e.currentTarget;
  const oldValue = target.value;
  setTimeout(() => {
    const newValue = target.value;
    if (oldValue && !newValue) {
      // Clear was clicked so do something here on clear
      return;
    }

    // Was a regular click so do something here
  }, 50);
};

对我来说,点击X应该算作一个更改事件是有意义的。我已经设置了onChange事件来做我需要它做的事情。所以对我来说,修复是简单地做这一行jQuery:

$('#search').click(function(){ $(this).change(); });

你也可以用一般的方式通过绑定onInput事件处理如下

<input type="search" oninput="myFunction()">

将搜索事件绑定到搜索框,如下所示-

$('input[type=search]').on('search', function () {
    // search logic here
    // this function will be executed on click of X (clear button)
});