我正在尝试创建一个下拉列表,它将根据所选的下拉列表显示不同的结果。下面是我关于复制的最小示例:
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";
};<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>
理想情况下,我想在
case (1):
hiddenDiv.style.display = "block";但我不确定这在这种情况下会起作用。
发布于 2020-05-28 15:44:55
除了@Jacob的答案之外,您似乎还应该为结果选项提供id而不是类。
ID可用于标识一个元素,而一个类可用于标识多个元素。
并在选择其他选项时,在onchange中清除选项。
Array.from(document.getElementsByClassName("result")[0].children, (child) => child.style.display = "none")否则的话,就会有很多选择。
此外,您还可以避免在您的情况下使用if语句。使用模板文字。
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"<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>
https://stackoverflow.com/questions/62068325
复制相似问题