[英]Setting the selected attribute on an option element for real using jQuery
I am generating a select list with option elements in jQuery. 我正在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);
But then the option does not have the selected attribute present. 但是该选项没有选定的属性。
$(sel).html()
gives something like: $(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>
I tried this approach (same result as using .val()): 我尝试了这种方法(与使用.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? 还有其他或更好的方法吗?
You could use the native setAttribute()
method . 您可以使用本机setAttribute()
方法 。 I believe jQuery muddles the distinction between attributes and properties. 我相信jQuery会混淆属性和属性之间的区别。
This gets the <option>
you want by its index from the <select>
element's options collection
, and sets the attribute: 这将通过<select>
元素的options collection
索引获取所需的<option>
,并设置属性:
sel[0].options[1].setAttribute('selected','selected');
Or this uses jQuery to set the value first, then goes back and gets the correct option using the native selectedIndex
property . 或者这使用jQuery首先设置值,然后返回并使用本机selectedIndex
属性获取正确的选项。
sel.val(1);
sel[0].options[sel[0].selectedIndex].setAttribute('selected','selected');
EDIT: Off topic a little, but you could create the <option>
elements a little differently like this: 编辑:关闭主题一点,但你可以创建<option>
元素有点不同,如下所示:
$("<option>",{
value: i,
html: v
}).appendTo(sel);
Since jQuery 1.4, you can send a collection of values you wish to set for a new element. 从jQuery 1.4开始,您可以发送一组要为新元素设置的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.