0
如果我在頁面上有多個'。typeahead'輸入字段,並且我希望他們每個人都能初始化typehead(),我如何爲一個specfic輸入元素沒有重複我的代碼?例如:如何在全局偵聽器上設置javascript屬性,無需複製代碼
我的領域:
<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">
(最後一個是我想打電話預輸入()領域,但隨着自動選擇設置爲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
});
});
個
問候,
邁克爾