jQuery Cannot set “selected”=“selected” via attr()

2019-01-14 09:13发布

问题:

<select>
    <option>1</option>
    <option>2</option>
    <option class="test">3</option>
</select>

$('.test').attr('selected', 'selected');​

The select box above would choose the third option as default without any issues. However, if you check the elements with Firebug there isn't any selected="selected" attribute present within the chosen <option>.

I know this isn't a big issue as it still works but I need selected="selected" there so my other scripts could catch it and perform further processing. Are there any workarounds out there?

Thanks.

回答1:

The selected attribute does not correspond to the current selectedness state of the option. The selected attribute corresponds to the default selectedness, which will be restored if .reset() is called (or a type="reset" button is clicked) on the form. The current selectedness state can be accessed using the DOM property selected, whereas the default-selectedness, as reflected by the attribute, is accessed under the DOM property defaultSelected.

The same goes for value vs defaultValue on <input type="text">/<textarea>, and checked/defaultChecked on type="checkbox"/"radio".

jQuery's attr() is misleadingly named, and its attempts to pretend attributes and properties are the same thing is flawed. When you use attr(), you are usually accessing the property, not the attribute. Consequently, $(el).attr('selected', 'selected') is actually doing el.selected= 'selected'. This works because 'selected', as with any non-empty string, is ‘truthy’: it gets converted to el.selected= true. But this does not at any point touch the selected="selected" attribute.

IE further complicates this already confusing situation by (a) getting getAttribute/setAttribute wrong so it accesses the properties instead of the attributes (which is why you should never use these methods in an HTML document), and (b) incorrectly mapping the current form state to the HTML attributes, so the attributes do actually appear in that browser.

but I need selected="selected" there

Why? Are you serialising the form to innerHTML? This won't include form field values (again, except in IE due to the bug), so is not a usable way to store field values.



回答2:

This works as expected, Check it out : http://jsfiddle.net/MZYN7/1/



回答3:

It should be $('.test').attr('selected', true);​

also

<option selected>value</option>

It will not show up as selected="selected"