javascript - 无法在 JavaScript 中使用此选择功能

标签 javascript html

我认为这真的很容易,但我就是无法让它发挥作用。

我希望我的按钮在选择不同选项时显示不同的内容。

我尝试过这个:

<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/

相关文章:

javascript - 浏览器窗口中的所有选项卡是否共享一个 JavaScript 线程?

javascript - Ajax 没有在提交时触发

javascript - 忽略 firefox 步骤不匹配表单验证

javascript - CSS:添加子div时div宽度增加

html - 最后更改页面方向

jquery - 我如何使这个 CSS/jQuery 下拉菜单多级?

javascript - 获取HTML元素隐藏值

javascript - CommonJS 中的自定义 `require` 方法(特别是 Node)

javascript - 无法生成多个图像

javascript - jQuery-Mobile pagecontainerbeforechange 不会触发