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

时间:2011-07-12 20:46:54

标签: jquery 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>

2 个答案:

答案 0 :(得分:40)

函数.live()现已弃用。

看起来像这样的代码有效:

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

答案 1 :(得分:11)

这有效:

$(function() {
  var options = {
    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
  };

  $("input.searchInput").live("keydown.autocomplete", function() {
    $(this).autocomplete(options);
  });

  var addInput = function() {
    var inputHTML = " <input name='search' value='' class='searchInput' maxlength='20' />";
    $(inputHTML).appendTo("form#myForm");
    $("input.searchInput:last").focus();
  };

  if (!$("form#myForm").find("input.searchInput").length) {
    addInput();
  }

  $("input#addButton").click(addInput);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<form id="myForm" name="myForm" method="post">
  <input id="addButton" name="addButton" type="button" value="Add an input" />
</form>