jQuery UI自动完成更改事件不会实时触发

时间:2017-04-15 22:10:40

标签: javascript jquery jquery-ui jquery-ui-autocomplete

使用jQuery UI,我试图在#tag输入的值发生更改后立即触发事件,但正如您所看到的那样log事件会在用户点击页面时触发而不是输入值改变后立即

我已经尝试将更改事件与paste绑定,但我得到了相同的结果。



 $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
    
     $("#tags").on('change', function(){
        console.log($(this).val());
    });
  } );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
 <div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
&#13;
&#13;
&#13;

你可以告诉我如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

据我所知,Javascript正在按预期执行。只有在Inputs值更改后才会触发Change事件。变化并不一定意味着价值变化的瞬间。更改表示输入的值已提交到其他值。如果你想在每次动作时发生某些事情,那么使用输入事件。

$( function() {
        var availableTags = [
          "ActionScript",
          "AppleScript",
          "Asp",
          "BASIC",
          "C",
          "C++",
          "Clojure",
          "COBOL",
          "ColdFusion",
          "Erlang",
          "Fortran",
          "Groovy",
          "Haskell",
          "Java",
          "JavaScript",
          "Lisp",
          "Perl",
          "PHP",
          "Python",
          "Ruby",
          "Scala",
          "Scheme"
        ];
        $( "#tags" ).autocomplete({
          source: availableTags
        });
        
         $("#tags").on('input', function(){
            console.log($(this).val());
        });
      } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<label>Input:</label>
<input type='text' value='' id='tags'/>

答案 1 :(得分:0)

我不确定您的确想要什么,但您可以使用keypresskeydown代替change,只要用户在输入中写入,代码就会触发。

$("#tags").on('keypress', function(){
    console.log($(this).val());
});