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

前端 未结 3 1874
星月不相逢
星月不相逢 2020-12-05 16:23


$(\'.test\').         


        
相关标签:
3条回答
  • 2020-12-05 16:44

    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.

    0 讨论(0)
  • 2020-12-05 17:03

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

    also

    <option selected>value</option>

    It will not show up as selected="selected"

    0 讨论(0)
  • 2020-12-05 17:05

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

    0 讨论(0)
提交回复
热议问题