jqueryui:" TypeError:this.menu.element未定义"

时间:2015-02-22 16:15:49

标签: javascript jquery jquery-ui

我正在尝试使用JavaScript创建的输入中创建一个jquery-ui自动完成窗口小部件,如下所示:

function drawAutocomplete() {
    var fooBox = document.createElement("input");
    fooBox.id = "foobox";
    fooBox.name = "foobox";

    window.document.firstChild.appendChild(fooBox);

    $("#foobox").autocomplete({source: ["eenie", "meenie"]});
}

但我一直在

TypeError: this.menu.element is undefined

每当我尝试与该框进行交互时,都不会显示自动完成备选方案。

是否无法以这种方式使用动态创建的项目?还有什么我可以误解的?

2 个答案:

答案 0 :(得分:2)

使用jQuery的简单方法:

function drawAutocomplete() {
    // used body, since I'm not sure what element you're reffering to
    $('<input type="text" id="foobox" name="foobox">').appendTo('body')
    // don't search the DOM for '#foobox', use created element:
    .autocomplete({source: ["eenie", "meenie"]});
}

DEMO


或者使用您的代码,将fooBox HTML元素包装到jQuery对象中。

function drawAutocomplete() {
   var fooBox = document.createElement("input");
   fooBox.id = "foobox";
   fooBox.name = "foobox";
   // used body, since I'm not sure what element you're reffering to
   document.body.appendChild(fooBox);
   $(fooBox).autocomplete({source: ["eenie", "meenie"]});
}

无论哪种方式,您都不必在DOM中搜索'#foobox',因为您已在此处缓存了该元素:var fooBox(第二个示例)或$('<input ...>')(第一个例子)。

DEMO

答案 1 :(得分:2)

您的元素未正确添加到页面中:

window.document.firstChild.appendChild(fooBox);

尝试将数据附加到doctype(或HTML)代码。

使用

window.document.body.appendChild(fooBox);

所以你的动态代码很好(简单的JS和jQuery的混合),但是一旦你将input添加到正确的元素,它应该可以正常工作。 @phillip100的答案向您展示了一种很好的优化方法。

演示:

$(document).ready(
function drawAutocomplete() {
    var fooBox = document.createElement("input");
    fooBox.id = "foobox";
    fooBox.name = "foobox";

    document.body.appendChild(fooBox);

    $("#foobox").autocomplete({source: ["eenie", "meenie"]});
});
<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.11.3/themes/smoothness/jquery-ui.css" />
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>