在下面的示例中,我创建了typeahead
类的实例
var ta = $.typeahead({
input: '.super',
minLength: 0,
maxItem: 15,
order: "asc",
hint: true,
href: "",
searchOnFocus: true,
display: ["name"],
template: "{{name}}",
source: {
"SearchResults": {
//ajax: {
// url: "/search/" + id,
// path: ""
//}
}
},
callback: {
onClickAfter: function (node, a, item, event) {
event.preventDefault;
debugger;
}
},
debug: true
});
稍后,并使用通过以下方法获得的id
变量
$("input").focus(function () {
id = $(this).attr("id");
ta.source.ajax.url = "/search/" + id;
});
i得到Cannot set property 'url' of undefined
,因为ta.source.ajax
实际上为空。我该如何解决?
简单地说,我不想为表单的每个输入创建重复的代码
通过Typeahead实例的SearchResults
配置options
property组。
source
生成的。options
ta.options.source.SearchResults.ajax.url = "/search/" + id;
而不是@freedomn建议的ta.source.SearchResults.ajax.url
ta.source.ajax.url
[另外,@ OrElse关于您的错误,请尝试将属性留空,不要将其注释掉。另外,尝试从SearchResults中删除双引号-
$("input").focus(function () { id = $(this).attr("id"); ta.source.SearchResults.ajax.url = "/search/" + id; });
source: {
SearchResults: {
ajax: {
url: "/search/" + id,
path: ""
}
}
},
当您将任何内容分配给“ ta”变量时,您可能会获得所有属性。但您收到错误消息“无法设置未定义的属性'URL'”。因此,您明确尝试使用的属性是URL。从逻辑上讲,它应该是ajax属性,但ajax本身未在您的变量中定义。因此,您应该首先定义ajax。
var ta = $.typeahead({ input: '.super', minLength: 0, maxItem: 15, order: "asc", hint: true, href: "", searchOnFocus: true, display: ["name"], template: "{{name}}", source: { "SearchResults": { //ajax: { // url: "/search/" + id, // path: "" //} } }, callback: { onClickAfter: function (node, a, item, event) { event.preventDefault; debugger; } }, debug: true });
始终确保事先定义了JSON变量,以后可以定义属性。例如
var ta = $.typeahead({ input: '.super', minLength: 0, maxItem: 15, order: "asc", hint: true, href: "", searchOnFocus: true, display: ["name"], template: "{{name}}", source: { "SearchResults": { ajax: { // now ajax is defined and you will not get any error. } } }, callback: { onClickAfter: function (node, a, item, event) { event.preventDefault; debugger; } }, debug: true });
但是如果您使用类似下面的内容。
var a={} a.b.c=10 console.log(a.b.c)// you will get same error.
希望这会对您有所帮助。
a.b={}
a.b.c=10
console.log(a.b.c)// you will not get an error.
是否存在以防止其引发null错误的属性,该怎么办?>ta.source.ajax