首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用div作为case参数创建开关/case语句?

如何使用div作为case参数创建开关/case语句?
EN

Stack Overflow用户
提问于 2020-05-28 15:20:05
回答 1查看 492关注 0票数 1

我正在尝试创建一个下拉列表,它将根据所选的下拉列表显示不同的结果。下面是我关于复制的最小示例:

代码语言:javascript
运行
复制
let elem = document.getElementById("dropdown");
elem.onchange = function(){
  if /*this is where I'm stuck. And on the following code. I want to say if the dropdown id = 1, 
  then show div option1_result*/
    let hiddenDiv = document.getElementById("option1_result");
    hiddenDiv.style.display = (this.value == "") ? "none":"block";
};
代码语言:javascript
运行
复制
<p>
Please select the dropdown:
</p>
<select id = "dropdown">
  <option id = "1" class = "selected"> option 1</option>
  <option id = "2" class = "selected"> option 2</option>
</select>

<div class = "result">
  <div class = "option1_result" style="display:none;">
    <p>
      Option 1 Result! 
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div class = "option2_result" style = "display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div>

理想情况下,我想在

代码语言:javascript
运行
复制
case (1):
  hiddenDiv.style.display = "block";

但我不确定这在这种情况下会起作用。

JSFiddle

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-28 15:44:55

除了@Jacob的答案之外,您似乎还应该为结果选项提供id而不是

ID可用于标识一个元素,而一个类可用于标识多个元素。

并在选择其他选项时,在onchange中清除选项。

代码语言:javascript
运行
复制
Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")

否则的话,就会有很多选择。

此外,您还可以避免在您的情况下使用if语句。使用模板文字

代码语言:javascript
运行
复制
const elem = document.getElementById("dropdown");
elem.addEventListener("change", () => {
  Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")
  const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"
})
const hiddenDiv = document.getElementById(`option${elem.value}_result`);
  hiddenDiv.style.display = "block"
代码语言:javascript
运行
复制
<p>
  Please select the dropdown:
</p>
<select id="dropdown">
  <option value="1" class="selected"> option 1</option>
  <option value="2" class="selected"> option 2</option>
</select>

<div class="result">
  <div id="option1_result" style="display:none;">
    <p>
      Option 1 Result!
      <button href="#">
      See More
      </button>
    </p>
  </div>
  <div id="option2_result" style="display:none;">
    <p>
      Option 2 result
      <button href="#">
      More about opt 2
      </button>
    </p>
  </div>
</div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62068325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档