在下面的示例中,我创建了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;
});
我得到CCD_ 3,因为CCD_。我该怎么解决?
简单地说,我不想为我的表单的每个输入创建重复的代码
通过Typeahead实例的options
属性配置SearchResults
组。
Typeahead实例的source
属性由options
生成。
ta.options.source.SearchResults.ajax.url = "/search/" + id;
我认为您应该使用ta.source.SearchResults.ajax.url
,而不是@freedomn
建议的ta.source.ajax.url
$("input").focus(function () {
id = $(this).attr("id");
ta.source.SearchResults.ajax.url = "/search/" + id;
});
此外,@OrElse关于您的错误,请尝试将属性留空,不要注释掉。另外,尝试从SearchResults中删除双引号--
source: {
SearchResults: {
ajax: {
url: "/search/" + id,
path: ""
}
}
},
也许您正在使用某种jQuery库。但是如果它正确地加载和初始化了您的变量。如果你得到了所有其他财产,那么这只是一个小问题。让我们讨论一个可能的案例并了解的问题
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
});
当你把任何东西赋给"ta"变量时,你可能得到了all属性。但您收到一个错误,"无法设置未定义的属性'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: { // now ajax is defined and you will not get any error.
}
}
},
callback: {
onClickAfter: function (node, a, item, event) {
event.preventDefault;
debugger;
}
},
debug: true
});
始终确保JSON的变量是预先定义的,您可以稍后定义属性。
例如
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.
希望这对你有帮助。
在if语句中换行,检查ta.source.ajax
是否存在,以防止其抛出null error 属性
if(ta.source.ajax){
ta.source.ajax.url = "/search/" + id;
}