jQuery自动完成

Sta*_*bie 10 jquery jquery-ui jquery-plugins jquery-ui-autocomplete

我有一个自动填充文本框,需要响应2个事件:

  • 当用户在文本框中输入内容时(我当前正在使用focusout假设用户完成输入时.因此,如果用户选中文本框,则表示用户已完成输入.)
  • 当用户选择自动完成值列表中的项目时(我正在使用自动完成的select事件来确定)

问题:

当用户选择自动完成值列表中的项目时,事件链focusout首先被调用,然后是select.在进入时focusout,我只能访问用户键入的内容,而不是用户选择的自动完成值列表 - 这就是我实际需要的内容.我该如何解决这个问题?

重现问题的步骤:

  1. 在文本框中,键入字母 a
  2. ActionScript从自动完成值列表中选择
  3. 观察console.debug消息:

    focusout event called
    a
    select event called
    ActionScript
    
    Run Code Online (Sandbox Code Playgroud)

这是代码:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <title>Data Matching</title>
    </head>
    <body>
        <form>
            <input id="1" type="text"></input>
            <input id="2" type="submit"></input>
        </form>

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

        <script>
        $('#1').autocomplete(
        {
            select: function (event, ui)
            {
                "use strict";
                console.debug('select event called');
                console.debug(ui.item.value);
            },
            source: ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"],

            minLength: 1
        });

        $('#1').focusout(function ()
        {
            "use strict";
            console.debug('focusout event called');
            console.debug($(this).attr('value')); //  At this point, I need the value that was selected from autocomplete. I only get the value that the user typed, though
        });
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

And*_*ker 8

这正是jQueryUI为以下内容引入特殊change事件的原因autocomplete:

如果字段模糊,则触发,如果值已更改; ui.item指的是所选项目.

此活动可以满足您的两个要求:

$("#1").autocomplete({
    /* snip */
    change: function(event, ui) {
        if (ui.item) {
            console.log("ui.item.value: " + ui.item.value);
        } else {
            console.log("ui.item.value is null");
        }
        console.log("this.value: " + this.value);
    }
});
Run Code Online (Sandbox Code Playgroud)
  • ui.item 当用户未从自动填充候选列表中选择值时,将不会定义.
  • 在另一方面,this.value永远是正确的.

这是一个例子:http://jsfiddle.net/33GJb/