如果我的页面上有多个'.typeahead'输入字段,并且我希望它们每个都初始化typehead(),如何在不复制代码的情况下为一个特定的输入元素设置异常?例如。:
我的领域:
<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
});
});
问候,
麦可
最佳答案
用这个
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);
关于javascript - 如何在全局监听器上设置javascript属性,而无需复制代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30790260/