2015-04-06 73 views
1

我有下拉列表:如何將屬性添加到下拉列表中的每個選項

<select> 
    <option value=""></option> 
    <option value="Bla">Bla</option> 
    <option value="Foo">Foo</option> 
</select>   

使用jQuery我想通過枚舉每個選項修改我的列表中添加自定義屬性level所以我的選擇會看起來像並且需要跳過列表中的第一個選項:

<select> 
    <option value=""></option> //skipping the first one 
    <option value="Bla" level="1">Bla</option> 
    <option value="Foo" level="2">Foo</option> 
</select> 

我該怎麼用jQuery做到這一點?

+0

所以,你要使用'jQuery'做什麼? – 2015-04-06 07:03:55

回答

2

可以使用$('select option:gt(0)')在具有指數1到n的所有選項重複:

$('select option:gt(0)').attr('level',function(i){ 
    return i+1; 
}); 

Working Demo

$('select option:gt(0)').each(function(i){ 
    $(this).attr('level',i+1) 
}); 

Working Demo

1
$('select').children('option').each(function(index, element) { 
    if (index) $(element).attr('level', index); 
}); 
1

您可以使用.attr()

$('select option:not(:first-child)').attr('level', function (i) { 
    return i + 1 
}) 
1

它能夠更好地使用由html5提供data-*屬性:

$('select option').filter(':not(:first)').attr('data-level', function(i) { 
 
    return $(this).index(); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<select> 
 
    <option value=""></option> <!--this has index = 0--> 
 
    <option value="Bla">Bla</option><!--this has index = 1--> 
 
    <option value="Foo">Foo</option><!--this has index = 2--> 
 
</select>

正如你可以在JS共見de有使用jQuery的attr()方法,你可以注意到它接受一個回調函數來根據需要用某些操作返回屬性值。
在這個特定情況下,我們使用在給定select中可用的option.index(),並且在回調中,返回語句對於應用該屬性是必需的。

+0

你能讓我明白你爲什麼返回'return $(this).index();'如果我不那麼我會得到什麼問題? – SpringLearner 2015-04-06 07:08:01

+0

@SpringLearner'.index()'返回位置索引,就像您在註釋中看到的一樣。 – Jai 2015-04-06 07:10:28

1

試試這個

$('select option').each(function(index,item){ 
    if(index>0) 
    { 
     $(item).attr('level',index); 
    } 
}) 

Demo

相關問題