jqueryui:"类型错误:this.menu.element未定义"

jqueryui: "TypeError: this.menu.element is undefined"

本文关键字:quot element 未定义 menu 类型 jqueryui 错误 this      更新时间:2024-03-01

我正试图用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

每当我尝试与方框交互时,都不会显示自动完成的替代选项。

以这种方式不可能使用动态创建的项目吗?我还能误解什么呢?

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

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>

使用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"]});
}

演示


或者使用您的代码,将fooBoxHTML元素包装到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 ...>')(第一个示例)。

演示