Setting the selected attribute on an option element for real using jQuery

假装没事ソ 提交于 2019-12-07 04:01:22

问题


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);

But then the option does not have the selected attribute present.

$(sel).html() gives something like:

<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()):

$.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?


回答1:


You could use the native setAttribute() method. I believe jQuery muddles the distinction between attributes and properties.

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');

Or this uses jQuery to set the value first, then goes back and gets the correct option using the native selectedIndex property.

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>",{
    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.



来源:https://stackoverflow.com/questions/4292679/setting-the-selected-attribute-on-an-option-element-for-real-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!