【问题标题】:In a HTML select element, why the last option that has selected=false is selected?在 HTML select 元素中,为什么选择了最后一个 selected=false 的选项?
【发布时间】:2022-07-16 10:51:43
【问题描述】:

我有一个select 元素,其中包含option 元素。有些选项将属性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>

似乎当没有元素将selected设置为true时,最后一个将selected设置为false的元素是创建元素时默认选择的元素。

这种行为并不直观,在这种情况下,我希望选择第一个带有未定义 selectedoption,而不是明确未选择的。

是什么导致了这种行为?它是在任何地方定义的吗?

【问题讨论】:

  • 无效。你使用selected="selected" 或者你根本不使用它。基本上,发生的事情是 HTML 看到您选择了该属性,并将选择它。检查以下链接:stackoverflow.com/questions/1033944/…

标签: html select selected


【解决方案1】:

问题在于disabled 是一个布尔属性。当它存在时,它处于打开状态,并且它具有什么值并不重要,因此具有selected 属性的最后一个元素被选中。即使你写了false,它仍然被解释为true(见What values can appear in the "selected" attribute of the "option" tag?)。

【讨论】:

    【解决方案2】:

    为什么使用selected False,你能解释一下目的吗? 试试看。

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

    【讨论】:

    • disabled 与没有selected 不同。
    • 你能解释一下为什么你要selected="false"。
    猜你喜欢
    • 2012-09-28
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多