如果我的页面上有多个'.typeahead'输入字段,并且我希望它们中的每一个都初始化typehead(),那么如何在不重复我的代码的情况下为一个specfic输入元素设置异常? E.g:
我的领域:
<input type="text" class="typehead_selector" id="coworkers">
<input type="text" class="typehead_selector" id="jobs">
<input type="text" class="typehead_selector" id="search" data-action="search">
(最后一个是我想调用typeahead()的字段,但是autoSelect设置为false。
我的剧本:
$(".typehead_selector").typeahead({
autoSelect: true, // all typehead initilization have autoSelect
updater: function (item) {
// logic here
}
// ... more logic stripped here
});
我的新剧本,对我来说似乎很脏?
$(".typehead_selector").each(function() { // added line
var auto_select = true; // added line
if($(this).data("action") == "search") { // added line
auto_select = false; // now my searchfield will not have autoSelect enabled, hooray. but still, isn't this messy code?
} // added line
$(this).typeahead({ // now listening on $(this) instead of $(".typehead_selector")
autoSelect: auto_select,
updater: function (item) {
// logic here
}
// ... more logic stripped here
});
});
问候,
迈克尔
答案 0 :(得分:1)
使用此
var options = {
autoSelect: true, // all typehead initilization have autoSelect
updater: function (item) {
// logic here
}
// ... more logic stripped here
}
$(".typehead_selector:not(#search)").typeahead(options);
options.autoSelect = false;
$("#seach").typeahead(options);