<option> 与点击链接



我正在建立自己的购物网站,我在这部分卡住了:

<label for="option">Option</label>
<select id="option">
<optgroup>
<option onclick="changeValueA()">Option A</option>
<option onclick="changeValueB()">Option B</option>
</optgroup>
</select>
<p>You choosed Option <span id="option-value"></span></p>
<script>

function changeValueA(){

document.getElementById("option-value").innerHTML = "Option A";
}
function changeValueB(){

document.getElementById("option-value").innerHTML = "Option B";
}
</script>

我想让"option-value"显示"选项"如果changeValueA()通过点击中的选项B来调用。

但是,代码不起作用。如果你能帮我这个忙,我将不胜感激!

option元素不响应点击事件(从下面添加的console.logs可以看出);您需要检查<select>的值:

// these functions never run:
function changeValueA() {
console.log("A") 
document.getElementById("option-value").innerHTML = "Option A";
}
function changeValueB() {
console.log("B")
document.getElementById("option-value").innerHTML = "Option B";
}
// This one will be triggered by the select's onchange handler,
// and passes the selected value in so you don't need multiple 
// similar functions:
function changeValue(val) {
document.getElementById("option-value").innerHTML = val;
}
<label for="option">Option</label>
<select id="option" onchange="changeValue(this.value)">
<optgroup>
<option onclick="changeValueA()">Option A</option>
<option onclick="changeValueB()">Option B</option>
</optgroup>
</select>
<p>You chose <span id="option-value"></span></p>

相关内容

  • 没有找到相关文章

最新更新