如何将 jquery ui 自动完成添加到动态创建的元素?

问题描述:

我试图让 jQueryUI AutoComplete 在动态创建的表单输入元素上触发,但它不起作用.我试过在 $.live() 中使用 keyup.autocomplete 和 keydown.autocomplete 作为绑定事件,但它绑定到新元素 - 只有页面上已有的元素.

I'm trying to get jQueryUI AutoComplete to trigger on dynamically created form input elements, but it's not working. I've tried using keyup.autocomplete and keydown.autocomplete as bind events in $.live(), but it's binding to the new elements - only those already on the page.

试试代码这里(尝试在第一个输入中输入ava",然后点击添加一个输入"并在新输入中输入相同的内容).

Try out the code here (try typing "ava" in the first input, then click "Add an Input" and type the same in the new input).

JavaScript:

JavaScript:

$(function() {
    $("input#addButton").click(function() {
        $("input.searchInput:last").clone(true).appendTo($(this).closest("form"));
        $("input.searchInput:last").val("");

    })

    $("input.searchInput").live("keydown.autocomplete", function() {
        $(this).autocomplete({
            source: [
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme"
                ],

            minLength: 2
        });
    })
});

HTML:

<form name="myForm" method="post">
    <input id="addButton" name="addButton" type="button" value="Add an input" />
    <input name="search" value="" class="searchInput" maxlength="20" />
</form>

函数 .live() 现已弃用.

Function .live() is deprecated now.

看起来像这样的代码:

var options = {
    source: ["ActionScript", "AppleScript"],
    minLength: 2
};
var selector = 'input.searchInput';
$(document).on('keydown.autocomplete', selector, function() {
    $(this).autocomplete(options);
});