如何獲取數組中索引位置的值,該數組的用戶使用自動完成選擇了哪個元素?自動完成jQuery插件:所選數組索引的值
例如,如果我進入有兩個元素作爲輸入的自動完成插件數組:
var arr = [];
arr[0] = "John";
arr[1] = "Paul";
然後,說用戶選擇了「保羅」,我如何才能選擇指數「1」的價值?
如何獲取數組中索引位置的值,該數組的用戶使用自動完成選擇了哪個元素?自動完成jQuery插件:所選數組索引的值
例如,如果我進入有兩個元素作爲輸入的自動完成插件數組:
var arr = [];
arr[0] = "John";
arr[1] = "Paul";
然後,說用戶選擇了「保羅」,我如何才能選擇指數「1」的價值?
當我明白你的問題,你可能只是做類似
function FindIndex(arr, searchValue){
for(var i = 0; i < arr.length; ++i){
if(arr[i] === searchValue){
return i;
}
}
}
這裁判http://docs.jquery.com/Attributes/val#val 說,你可以使用一個選擇,像這樣:
$('#selection option:selected')....
var arr = [];
arr[0] = "John";
arr[1] = "Paul";
...
//user selects something
//assuming select value now is in an input field
var index = jQuery.inArray($("input#yourselector").val(), arr);
if (index > -1)
alert(index);
else
alert("value not found in autocomplete array");
jQuery的方式: 如果您的自動完成源是普通數組(即不是標籤值對或URL的數組),那麼您可以執行
$.inArray(ui.item.value,myAutocompleteSource)
例如
$('.my-autocompletes').autocomplete({ source:['Option1','Option2','Option3'], select: function(event, ui) { alert('Your selected a string with index '+ $.inArray(ui.item.value,$(_self).autocomplete('option','source')) ); } });
如果源是標籤 - 值對的陣列,則可以做
var index = -1;
$(_self).autocomplete('option','source')).each(function(idx) {
if (this.label == ui.item.label) { index=idx; return false; }
});
alert('You selected a string with index '+index);
當然,$(_self).autocomplete('option','source'))
可以直接引用自動完成的源代替項目。
也可以用jQuery find()方法做到這一點。 http://docs.jquery.com/Traversing/find#expr – Cheeso 2009-12-18 19:33:39