设置一个选项元素所选属性真正使用jQuery [英] Setting the selected attribute on an option element for real using jQuery
问题描述
我生成与jQuery的选项元素的选择列表。简化它看起来是这样的:
I am generating a select list with option elements in jQuery. Simplified it looks like this:
var sel = $("<select>");
$.each(data, function(i, v){
$("<option>").attr({ "value": i }).html(v).appendTo(sel);
});
然后我想选择一个选项。通常我会做这样的事情:
Then I want an option to be selected. Normally I would do something like:
$(sel).val(1);
但随后的选项没有选定属性present。
But then the option does not have the selected attribute present.
$(SEL)的.html()
给出这样的:
<option value="1">1</option>
<option value="2">2</option>
这就是我所期待的:
and this is what I expected:
<option value="1" selected="selected">1</option>
<option value="2">2</option>
我试过这个方法(效果与使用.VAL()):
I tried this approach (same result as using .val()):
$.each(data, function(i, v){
var attrs = { "value": i };
if(i == 1){
attrs.selected = "selected";
}
$("<option>").attr(attrs).html(v).appendTo(sel);
});
但我发现工作的唯一方法是:
but the only way I found working is:
$.each(data, function(i, v){
var el = "<option>";
if(i == 1){
el = '<option selected="selected"></option>';
}
$(el).attr({ "value": i }).html(v).appendTo(sel);
});
有没有其他的或更好的办法吗?
Is there any other or better way?
推荐答案
您可以使用本地的setAttribute()
方法。我相信jQuery的muddles特性和属性之间的区别。
You could use the native setAttribute()
method. I believe jQuery muddles the distinction between attributes and properties.
这得到&LT;选项&GT;
通过从的 &LT;选择&GT;
元素的 选项集合
,并设置属性:
This gets the <option>
you want by its index from the <select>
element's options collection
, and sets the attribute:
sel[0].options[1].setAttribute('selected','selected');
或者这使用jQuery首先设置值,然后返回和使用的本地的selectedIndex
属性。
sel.val(1);
sel[0].options[sel[0].selectedIndex].setAttribute('selected','selected');
编辑:题外话了一点,但你可以创建&LT;选项&GT;
元素有点不同是这样的:
Off topic a little, but you could create the <option>
elements a little differently like this:
$("<option>",{
value: i,
html: v
}).appendTo(sel);
由于jQuery的1.4,你可以发送值的集合你希望一个新的元素设置。
Since jQuery 1.4, you can send a collection of values you wish to set for a new element.
这篇关于设置一个选项元素所选属性真正使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!