简体   繁体   English

在 HTML select 元素中,为什么选择了最后一个 selected=false 的选项?

[英]In a HTML select element, why the last option that has selected=false is selected?

I have a select element with option elements in it.我有一个包含option元素的select元素。 Some of the options have attribute selected set to false, and some don't have it set at all.有些选项的属性selected设置为 false,有些则根本没有设置。

 <select> <option selected=false>1</option> <option selected=false>2</option> <option>3</option> <option selected=false>4</option> <option>5</option> <option>6</option> </select>

It seems that when no elements have selected set to true , the last element with selected set to false is the one selected by default when the element is created.似乎当没有元素selected设置为true时, selected设置为false的最后一个元素是创建元素时默认选择的元素。

This behavior is not intuitive, and in this case I would expected the first option with undefined selected to be selected, and definitely not one that is explicitly unselected.这种行为不直观,在这种情况下,我希望selected未定义的第一个option ,并且绝对不是明确未选择的选项。

What causes this behavior?是什么导致了这种行为? Is it defined anywhere?它是否在任何地方定义?

The problem is that disabled is a boolean attribute.问题是disabled是一个布尔属性。 When it is present, it is on, and it doesn't matter what value it has, so the last element that has the selected attribute gets selected.当它存在时,它处于打开状态,并且它具有什么值并不重要,因此具有selected属性的最后一个元素被选中。 Even though you write false , it is still interpreted as true (see What values can appear in the "selected" attribute of the "option" tag? ).即使你写false ,它仍然被解释为true (参见What values can appear in the "selected" attribute of the "option" tag? )。

Why are using selected False can you please explain the purpose.为什么使用selected False,你能解释一下目的吗? Try it.试试看。

<select>
  <option disabled>1</option>
  <option disabled>2</option>
  <option>3</option>
  <option disabled>4</option>
  <option>5</option>
  <option>6</option>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM