我正在調試「城市」輸入字段上的jQuery自動完成實例(v1.1)。jQuery自動完成:用戶輸入中缺少字符
僅當字段值長度至少爲2且僅當值已更改時,纔會在字段的keyup
事件上設置自動完成數據綁定。
數據綁定,提示列表和自動完成工作正常。 但有些事情是錯的。在日誌中,我發現很多次在發佈到服務器的城市輸入值中缺少第三個甚至第四個字符。一些示例:
"trpani" instead of "trapani"
"fienze" instead of "firenze"
"scndicci" instead of "scandicci"
"brdisi" instead of "brindisi"
"paermo" instead of "palermo"
"caliari" instead of "cagliari"
我沒有成功複製該錯誤,但我確信它不會是偶然的!錯誤發生在第三個字符處。看來在插入過程中,Javascript處理與鍵盤緩衝區碰撞。
所以,我想但我不確定,人們輸入f i r e n z e
,但最終r
字符錯過了,輸入的最終值是fienze
,最終發送到服務器。
問題
這是怎麼回事?爲什麼我不能成功複製錯誤?哪裏不對?
這裏是用來設置自動完成的代碼:
/*
* here I store the previous value
*/
var storeCity;
$('#City').keydown(function(){
var val = $(this).val();
storeCity = (val.length >=2 ? val.substring(0,2):"");
});
/*
* the autocomplete is set only if
* - the City value has changed compared to the storeCity value
* - the City value has lenght at least 2
* - remark: using the keypress does not solve the issue
*/
$('#City').keyup(function(){
var val = $(this).val();
if(val.length>=2 && val.substring(0,2)!=storeCity){
getLocations('#City');
}
});
function getLocations(cityId){
var hint = $(cityId).val().substring(0,2);
$.ajax({
type: "GET",
url: "/include/getLocations.asp",
data: ({location : hint}),
async: false,
error: function() {},
success: function(dataget) {
var result = dataget.split("\n");
$(cityId).flushCache();
$(cityId).autocomplete(result, {
pleft: 100px,
minChars: 2,
matchContains: true,
max: 3000,
delay: 100,
formatItem: function(row){...},
formatMatch: function(row){ return row[0]; },
formatResult: function(row){ return row[0]; }
});
$(cityId).result(function(event,data){...});
}
});
}
好像有在喲一個問題因爲您首次調用getLocations()時storeCity的邏輯實現將始終等於空字符串。因爲你在keydown回調函數上設置它。嘗試使用按鍵,而不是在按鍵之前始終調用。 –
不,我已經測試過,但問題沒有解決。 –
您未正確使用自動填充小部件。你應該將它應用一次到'input'。 –