【问题标题】:How to make dropdown choices that change text or paragraph below the dropdown如何进行下拉选择以更改下拉列表下方的文本或段落
【发布时间】:2018-07-30 09:54:42
【问题描述】:
我在互联网上搜索了一整天,但我找不到解决我的问题的方法,我的问题对你们来说可能很简单,但作为一个新手,我无法真正解释清楚。在这里,我想从下拉列表中创建一个选项,当用户从选项中进行选择时,每次用户在下拉列表中更改其选择时,都会显示或更改一个文本行。
• 选项 1
• 选项 2
• 选项 3
任何类型的文本
**如果用户选择选项 1,下面会显示一个指定的文本,如果用户在下拉列表中选择选项 2,下面的文本将更改为选项 2 的指定,那么选项 3 相同。我希望你们明白我的意思。非常感谢您的帮助。
【问题讨论】:
标签:
javascript
html
drop-down-menu
web
css-transitions
【解决方案1】:
给select的onchange添加一个函数,并传递选中选项的值
function showPara(val) {
// check if the value is not empty or undefined
if (val !== undefined && val !== "") {
// then selelct all the p element which have a common class and add the coass which hide the element
document.querySelectorAll(".pClass").forEach(function(item) {
item.classList.add("hidePara");
// remove the class hide element where the id of p matches with the selected value
document.getElementById(val).classList.remove('hidePara')
})
}
}
.hidePara {
display: none;
}
.pClass {
color: red;
}
<select onchange="showPara(this.value)">
<option>Select</option>
<option value ='1'>Option 1</option>
<option value ='2'>Option 2</option>
<option value ='3'>Option 3</option>
<option value ='4'>Option 4</option>
</select>
<p id="1" class="pClass hidePara">Para 1</p>
<p id="2" class="pClass hidePara">Para 2</p>
<p id="3" class="pClass hidePara">Para 3</p>
<p id="4" class="pClass hidePara">Para 4</p>