首页 > 解决方案 > 如何在 javascript 中使用 this.value 从下拉列表中检查特定值

问题描述

我有一个下拉选择列表,其中大约有 10 个选项与一个隐藏的 div 连接,当使用 javascript 代码仅选择特定 3 个选项中的任何一个时应该显示

document.getElementById('item').addEventListener('change', function () {
var style = (this.value == "661056067" or this.value == "571855424") ? 
'table-row' : 'none';
document.getElementById('hidden_div').style.display = style;
});

我尝试了上面显示的代码,因为我希望 this.value 函数等于多个值,但它不起作用。那么让ot工作的正确方法是什么。请注意,我一点也不擅长 javascript。谢谢你的帮助

标签: javascripthtml-selectgetelementbyid

解决方案


而不是or使用||

document.getElementById('item').addEventListener('change', function () {
    var style = (this.value == "661056067" || this.value == "571855424") ? 
    'table-row' : 'none';
    document.getElementById('hidden_div').style.display = style;
});

您也可以使用includes.

document.getElementById('item').addEventListener('change', function () {
    var style = ["661056067", "571855424"].includes(this.value) ? 'table-row' : 'none';
    document.getElementById('hidden_div').style.display = style;
});

推荐阅读