Html控件视觉值与代码不一致

问题描述 投票:0回答:0

我有以下内容:

const select_clicked = select => {
  const selectedIndex = select.selectedIndex;
  console.log(selectedIndex);
  const output = document.getElementById("output");
  const selectedOption = select.options[select.selectedIndex];
  const color = selectedOption.innerText;
  output.innerText = selectedIndex + " " + color;
  output.setAttribute("class", color);
}

document.addEventListener("DOMContentLoaded", (e) => {
  console.log("ran")
  const select = document.getElementById("select");
  select_clicked(select);
});
  .Blue { background-color: blue; color: white}
    .Green { background-color: green; color: white}
    .Red { background-color: red; color: white}
 
<body>
    <select id="select" onchange="select_clicked(this);">
      <option value="B">Blue</option>
      <option value="G">Green</option>
      <option value="R">Red</option>
    </select>
    <p>Selected Index: <span id="output" style="padding:0.5rem">initial value</span></p>
    <hr>
    <a href="https://google.com">Navigate out</a>
    <hr>
    <p>Steps: select drop down to something other than blue. Navigate to another page. Do a browser Back back to this page.</p>
</body>

如果下拉菜单被选择为蓝色以外的其他内容,用户导航出页面,然后通过浏览器的后退功能返回页面,下拉菜单直观地显示原始选择的选项,但以编程方式,

 selectedIndex
属性回到0.

如果这种行为是故意的?当用户返回时,我如何找出下拉控件的真实状态,或者如何根据原始 Html 将下拉菜单可视化地重置为情况?

dom dhtml
© www.soinside.com 2019 - 2024. All rights reserved.