我认为这真的很容易,但我就是无法让它发挥作用。
我希望我的按钮在选择不同选项时显示不同的内容。
我尝试过这个:
<select id="selector123">
<option>test</option>
<option>tes2</option>
</select>
<br><br>
<button onclick="test()">hoi</button>
<script>
var e = document.getElementById("selector123");
var strUser =
e.options[e.selectedIndex].value;
function test() {
if (strUser =
"test") {
alert('this should a different text');
} else if (strUser = "tes2") {
alert('this should say this text');
}
}
</script>
但它不起作用。
也许知道我做错了什么?
最佳答案
问题是您仅在加载时设置 strUser
的值,如果您将其移动到 test()
函数内,它将在您每次单击时更新按钮。您还使用了错误的比较运算符,应该是 ===
:
<select id="selector123">
<option>test</option>
<option>tes2</option>
</select>
<br><br>
<button onclick="test()">hoi</button>
<script>
var e = document.getElementById("selector123");
function test() {
var strUser = e.options[e.selectedIndex].value;
if (strUser === "test") {
alert('this should a different text');
} else if (strUser === "tes2") {
alert('this should say this text');
}
}
</script>
关于javascript - 无法在 JavaScript 中使用此选择功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552634/