$('#list option').each(function(){
//do stuff
});
循環遍歷一個列表中的選項。 我想知道如何才能得到當前循環的索引?
因爲我不想必須var i = 0; 和循環內有i ++;
$('#list option').each(function(){
//do stuff
});
循環遍歷一個列表中的選項。 我想知道如何才能得到當前循環的索引?
因爲我不想必須var i = 0; 和循環內有i ++;
$('#list option').each(function(index){
//do stuff
alert(index);
});
警報的指數:)
和*不*,例如`function(value | element,index | key)`,就像等效的本地方法`forEach`和其他所有流行的API一樣。 – Barney 2013-12-05 14:41:00
的jQuery負責爲你處理。 .each()
回調函數的第一個參數是循環當前迭代的索引。第二個是當前匹配的DOM元素所以說:
$('#list option').each(function(index, element){
alert("Iteration: " + index)
});
$('#list option').each(function(intIndex){
//do stuff
});
.each(function(index, Element))
function(index, Element)A function to execute for each matched element.
所以你需要使用:
$('#list option').each(function(i,e){
//do stuff
});
...其中索引將作爲索引,元素將成爲列表中的選項元素
驚訝地發現,沒有給出這種語法。
.each
語法與數據或收集
jQuery.each(collection, callback(indexInArray, valueOfElement));
OR
jQuery.each(jQuery('#list option'), function(indexInArray, valueOfElement){
//your code here
});
閱讀API,也許...... http://api.jquery.com/each/ – 2010-12-03 02:46:48