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

前端之家收集整理的这篇文章主要介绍了如何将jquery ui autocomplete添加到动态创建的元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图让jQueryUI AutoComplete在动态创建的表单输入元素上触发,但它不起作用.我已经尝试使用keyup.autocomplete和keydown.autocomplete作为$.live()中的绑定事件,但它绑定到新元素 – 只有已经在页面上的元素.

尝试代码here(尝试在第一个输入中键入“ava”,然后单击“添加输入”,并在新输入中键入相同).

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()已被弃用.

看起来像这样的代码

var options = {
    source: ["ActionScript","AppleScript"],minLength: 2
};
var selector = 'input.searchInput';
$(document).on('keydown.autocomplete',selector,function() {
    $(this).autocomplete(options);
});
原文链接:https://www.f2er.com/jquery/180465.html

猜你在找的jQuery相关文章