Javascript 如何向下拉列表的每个选项添加属性
我有下拉列表:Javascript 如何向下拉列表的每个选项添加属性,javascript,jquery,Javascript,Jquery,我有下拉列表: <select> <option value=""></option> <option value="Bla">Bla</option> <option value="Foo">Foo</option> </select> 如何使用jQuery实现这一点?您可以使用$'select option:gt0'迭代索引为1到n的所有选项: 或
<select>
<option value=""></option>
<option value="Bla">Bla</option>
<option value="Foo">Foo</option>
</select>
如何使用jQuery实现这一点?您可以使用$'select option:gt0'迭代索引为1到n的所有选项: 或
您可以使用$'select option:gt0'迭代索引为1到n的所有选项: 或 您可以使用.attr 您可以使用.attr 最好使用html5提供的data-*属性: $'select option'.filter':not:first'.attr'data-level',functioni{ 返回$this.index; } 布拉 福 最好使用html5提供的data-*属性: $'select option'.filter':not:first'.attr'data-level',functioni{ 返回$this.index; } 布拉 福 试试这个
$('select option').each(function(index,item){
if(index>0)
{
$(item).attr('level',index);
}
})
试试这个
$('select option').each(function(index,item){
if(index>0)
{
$(item).attr('level',index);
}
})
那么你想用jQuery做什么呢?那么你想用jQuery做什么呢?你能让我明白为什么你要返回`return$this.index;`如果我不这样做,我会遇到什么问题?@SpringLearner.index返回职位索引,就像你在评论中看到的那样。你能告诉我为什么返回'return$this.index;'如果我不这样做,我会遇到什么问题?@SpringLearner.index返回位置索引,就像你在评论中看到的那样。
$('select option:gt(0)').each(function(i){
$(this).attr('level',i+1)
});
$('select').children('option').each(function(index, element) {
if (index) $(element).attr('level', index);
});
$('select option:not(:first-child)').attr('level', function (i) {
return i + 1
})
$('select option').each(function(index,item){
if(index>0)
{
$(item).attr('level',index);
}
})