【发布时间】:2019-09-04 09:59:08
【问题描述】:
我已经搜索过,但找不到解决问题的方法。我不是 JS 专家,只是一个新手,但我不明白为什么这只能工作一次。 我有一个 SELECT 下拉列表,我想在选择的不同选项上执行不同的指令。
我有 4 个 html 文本块,只有 1 个是可见的(显示:块),其他是隐藏的(显示:无)。我想在这里实现的是在单击按钮时仅显示选定的块并隐藏其他块。
这是我得到的代码:
function filter() {
if (document.getElementById('dynamic_select').value == 'opt1') {
document.getElementById('html_block_1').style.display = 'block';
document.getElementById('html_block_2').style.display = 'none';
document.getElementById('html_block_3').style.display = 'none';
document.getElementById('html_block_4').style.display = 'none';
}
if (document.getElementById('dynamic_select').value == 'opt2') {
document.getElementById('html_block_2').style.display = 'block';
document.getElementById('html_block_1').style.display = 'none';
document.getElementById('html_block_3').style.display = 'none';
document.getElementById('html_block_4').style.display = 'none';
}
if (document.getElementById('dynamic_select').value == 'opt3') {
document.getElementById('html_block_3').style.display = 'block';
document.getElementById('html_block_1').style.display = 'none';
document.getElementById('html_block_2').style.display = 'none';
document.getElementById('html_block_4').style.display = 'none';
}
if (document.getElementById('dynamic_select').value == 'opt4') {
document.getElementById('html_block_4').style.display = 'block';
document.getElementById('html_block_1').style.display = 'none';
document.getElementById('html_block_2').style.display = 'none';
document.getElementById('html_block_3').style.display = 'none';
}
}
<select id="dynamic_select">
<option value="opt1">Display html block 1</option>
<option value="opt2">Display html block 2</option>
<option value="opt3">Display html block 3</option>
<option value="opt4">Display html block 4</option>
</select>
<button onClick="filter()">Filter</button>
当我选择一个选项并单击按钮时,它会按预期工作。但是当我选择其他选项并第二次单击该按钮时 - 它什么也不做。该函数只执行一次。
有什么简单的方法可以解决吗?
【问题讨论】:
-
if (document.getElementById('dynamic_select').value == 'opt4'){...位于您的filter函数之外 -
您的代码在控制台中抛出错误。有一个无与伦比的
} -
抱歉,打错了。一}太多了。但是在原始代码中这不是问题,它仍然无法正常工作。
-
请同时添加 html 块。
-
没有错字对我有用,检查this JSFiddle
标签: javascript function if-statement onclick