jQuery自动完成选择事件和输入字段关系上的模糊事件

时间:2016-07-18 09:07:51

标签: jquery jquery-ui autocomplete onblur

我对jQuery UI Autocomplete组件有疑问。我按以下方式初始化组件:

newdata

当我在浏览器中尝试此代码并从自动填充下拉列表中选择一项时,我始终会在Chrome控制台中var $input = $('#autocompleteInput'); $input.autocomplete({ source: source, appendTo: appendToSelector, select: function(event, ui) { console.log('select'); }, minLength: 0 }); //... $input.on('blur', function(e) { console.log('blur'); }); 之前看到selected

  

选择

     

模糊

当我从自动完成中选择一个项目时,我能确定这两个侦听器总是以这个顺序执行(先选择并在之后模糊)吗?我怎样才能确定执行的顺序总是如此?

感谢您的关注。

1 个答案:

答案 0 :(得分:1)

简短地回答你的问题,没有。有许多方案可以产生许多不同的组合。

以下是一些测试:

https://jsfiddle.net/Twisty/b4nyguqd/

<强> HTML

<div>
  <label>Search:</label>
  <input id="autocompleteInput" type="text" />
</div>
<div class="wrapper">
  <div id="eventLog">
  </div>
</div>

<强>的jQuery

function upEvent(log) {
  var d = new Date();
  var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
  $("#eventLog").append("<p>" + time + " - " + log + "</p>\r\n");
}
$(function() {
  var source = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];
  var $input = $('#autocompleteInput');
  var appendToSelector = "#someElem";
  $input.autocomplete({
    source: source,
    select: function(event, ui) {
      upEvent(event.type);
    },
    minLength: 0
  });

  $input.on('blur', function(e) {
    upEvent(e.type);
  });
});

作为用户,我只能做一些事情,但是例如这里是我测试的前几个:

  1. 键入&#39; app&#39;,结果显示:&#39; AppleScript&#39;
  2. 向下箭头直到AppleScript&#39;突出显示
  3. 按Return键
  4. 删除直到只有&#39; A&#39;遗体
  5. 向下箭头指向&#39; ActionScript&#39;
  6. 按Return
  7. 在文本字段外的页面上单击鼠标
  8. 结果:

    10:35:18 - autocompleteselect
    10:35:24 - autocompleteselect
    10:35:26 - blur
    

    正如您所看到的,我已经执行了正常操作,但blur从未被触发,因为我从未失去测试场的焦点。

    <强>更新

    发表评论后,您可以看到:

    https://jsfiddle.net/Twisty/b4nyguqd/2/

    我的结果:

    13:54:2 - Temp value updated: AppleScript
    13:54:2 - autocompleteselect
    13:54:6 - Temp Value during blur: AppleScript
    13:54:6 - blur
    13:54:14 - Temp value updated: Asp
    13:54:14 - autocompleteselect
    13:54:20 - Temp Value during blur: Asp
    13:54:20 - blur
    

    另一个测试缺少选择并且还选择了不带模糊事件的不同值:

    13:56:16 - Temp Value during blur: undefined
    13:56:16 - blur
    13:56:22 - Temp value updated: C++
    13:56:22 - autocompleteselect
    13:56:23 - Temp Value during blur: C++
    13:56:23 - blur
    13:56:28 - Temp value updated: C
    13:56:28 - autocompleteselect
    13:56:32 - Temp value updated: C++
    13:56:32 - autocompleteselect
    13:56:34 - Temp Value during blur: C++
    13:56:34 - blur