我正在尝试创建一个下拉菜单,其中包含为每个选项显示不同警报消息的选项。
例如,使用选项" Algebra"创建了一个下拉菜单。 "化学"和"英语3"。我想要一个警报"需要几何课程"弹出代数。 "需要生物学课程"化学,"英语需要英语1和2课程。
我该怎么做?谢谢!我几乎只需要帮助这个功能。
<select id="test-dropdown" onchange="choice1(this)">
<option value="1">Algebra</option>
<option value="2">Chemistry</option>
<option value="3">English 3</option>
</select>
答案 0 :(得分:0)
这是一个示例 - 我没有使用警报,而是更改页面上的文本 我还将事件处理程序定义移动到脚本而不是内联
注意我还添加了“请选择”,因为如果在加载时已经选择了代数,则无法显示代数的文本
var choices = ["","Geometry course required","Biology course required","English 1 and 2 courses required"];
window.onload=function() {
document.getElementById("test-dropdown").onchange=function() {
document.getElementById("choice").innerHTML=choices[this.value];
}
document.getElementById("test-dropdown").onchange(); // show default
}
<select id="test-dropdown">
<option value="0">Please select</option>
<option value="1">Algebra</option>
<option value="2">Chemistry</option>
<option value="3">English 3</option>
</select>
<span id="choice"></span>
没有请选择
var choices = ["","Geometry course required","Biology course required","English 1 and 2 courses required"];
window.onload=function() {
document.getElementById("test-dropdown").onchange=function() {
document.getElementById("choice").innerHTML=choices[this.value];
}
document.getElementById("test-dropdown").onchange(); // show default
}
<select id="test-dropdown">
<option value="1">Algebra</option>
<option value="2">Chemistry</option>
<option value="3">English 3</option>
</select>
<span id="choice"></span>
带警报
var choices = ["","Geometry course required","Biology course required","English 1 and 2 courses required"];
window.onload=function() {
document.getElementById("test-dropdown").onchange=function() {
if (this.value !== 0) alert(choices[this.value]);
}
}
<select id="test-dropdown">
<option value="0">Please select</option>
<option value="1">Algebra</option>
<option value="2">Chemistry</option>
<option value="3">English 3</option>
</select>
<span id="choice"></span>
答案 1 :(得分:0)
var a = document.getElementById('test-dropdown');
a.addEventListener('change',function(){
var b = document.querySelectorAll('option:checked');
for(var i = 0; i < b.length; i++){
if(b[i].value == 1){
alert('Geometry course required')
}else if(b[i].value == 2 ){
alert('Biology course required')
}else{
alert('English 1 and 2 courses required for English')
}
}
});
<select id="test-dropdown">
<option value="0">select option</option>
<option value="1">Algebra</option>
<option value="2">Chemistry</option>
<option value="3">English 3</option>
</select>
答案 2 :(得分:-1)
也可以在[codepen](https://codepen.io/scodek/pen/EboEQp),
中查看function choice1(selected)
{
if(selected.options[selected.selectedIndex].text === "Algebra")
{
alert("Geometry course required");
}
else if(selected.options[selected.selectedIndex].text === "Chemistry")
{
alert("Biology course required");
}
else if(selected.options[selected.selectedIndex].text === "English 3")
{
alert("English 1 and 2 courses required for English");
}
}