我编写了这段代码,用于将 attr
添加到在 index
变量上定义了值的选项元素:
$(document).ready(function (){
$('option').each(function() {
var index = '1';
if($(this).attr('value') == index)
$(this).attr('selected','selected');
});
});
如何将 attr 添加到具有 index
变量上列出的值的每个元素。像这样的事情:
var index = '1,2,5,8,7,9';
if($(this).attr('value') == index)
...
更新: 这是我的 html 代码:
<select name="category[]" multiple="multiple" id="category">
<option class="level-0" value="1">Jobs</option>
<option class="level-1" value="24">CSS</option>
<option class="level-0" value="5">Products</option>
</select>
最佳答案
$('#category option').each(function() {
var index = [1,2,5,8,7,9],
value = parseInt( this.value, 10); // convert the value to integer
if($.inArray(value, index) >= 0)
$(this).attr('selected','selected'); //or, $(this).prop('selected', true);
});
<小时/>
没有数组
$('#category option').each(function() {
var index = '1,2,5,8,7,9',
value = this.value;
if(index.indexOf(value) >= 0)
$(this).attr('selected','selected'); //or, $(this).prop('selected', true);
});
<小时/>
使用filter()
var index = '1,2,5,8,7,9';
$('#category option').filter(function() {
return index.indexOf(this.value) >= 0;
}).attr('selected', 'selected');
<小时/>
使用.attr('selected',callback)
var index = '1,2,5,8,7,9';
$('#category option').attr('selected', function(i, val) {
if( index.indexOf( this.value) >= 0 )
return 'selected';
})
关于jQuery : add attr to each element based on values list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12455758/