我有一些jQuery代碼,以根據用戶輸入as per a previous question關注<select>
下拉列表。那就是:jQuery keypress()處理程序:管理事件流程
HTML
<select id="poetslist">
<option value="shakespeare" data-initial="WS">William Shakespeare</option>
<option value="milton" data-initial="JM">John Milton</option>
<option value="keats" data-initial="JK">John Keats</option>
<option value="wordsworth" data-initial="WW">William Wordsworth</option>
<option value="larkin" data-initial="PL">Phillip Larkin</option>
</select>
的JavaScript
$("#userlist").keypress(function (e) {
initials += String.fromCharCode(e.which).toUpperCase();
// when the relevant initials are typed, select that item
$(this).find("option").filter(function() {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
$('#book_results').html(loading_img); // Show 'loading' gif
// Then use get_books function to update some HTML on the page with relevant info
get_books($(this).find("option").filter(function() {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().val(), null, null);
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
timer = null;
initials = "";
}, 2000); // Max 2 second pause allowed between key presses
return false;
});
這是非常有前途的,但我發現,當用戶鍵入如首先選擇'WW','威廉莎士比亞',並且頁面上的所有HTML都會更新爲他,並且只有在幾秒鐘後,下拉才能「趕上」並更新爲「威廉華茲華斯」。
我敢肯定,這是我的錯,沒有正確處理事件的流程,但任何人都可以提出解決方案?注:我不能保證每個項目都有兩個首字母縮寫。
感謝您幫助JavaScript新手!