我正在从一个JavaScript数组创建一个下拉列表.我想在 Select 某些选项时显示范围.

例如,我想在 Select 了选项"a"和"c"而没有 Select "b"时显示跨度.

var city = ["a","b","c"];

// Add array to city dropdown
var select_city = document.getElementById("city");

for(var i = 0; i < city.length; i++) {
    let opt = city[i];
    let el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select_city.appendChild(el);
};

// Display output
var output = document.getElementById("output");

select_city.onchange = function() {
    output.style.display = (this.value == city.value && this.value == !"b") ? "block":"none";
};
#output {
    display: none;
}
<select name="city" id="city">
    <option value="-">- Choose city -</option>
</select>

<span id="output"></span>

为什么这不管用?我怎样才能正确地做这件事?

推荐答案

这种比较逻辑有点不对劲:

this.value == city.value && this.value == !"b"

没有city.value,因为city等于an array.您可以判断数组includes this.value:

city.includes(this.value)

另外,!"b"没有多大意义. 要判断某个值是否为not equal,请使用!=(或!==)运算符:

this.value != "b"

结果是:

city.includes(this.value) && this.value != "b"

Javascript相关问答推荐

无法将nPM simplex-noise包导入在JS项目中工作

使用TMS Web Core中的HTML模板中的参数调用过程

node TS:JWT令牌签名以验证客户端和后台问题之间的身份验证

模块与独立组件

GrapeJS -如何保存和加载自定义页面

togglePopover()不打开但不关闭原生HTML popover'

Angular material 拖放堆叠的牌副,悬停时自动展开&

如何从Intl.DateTimeFormat中仅获取时区名称?

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

如何使用JavaScript拆分带空格的单词

用JS从平面文件构建树形 struct 的JSON

未加载css colored颜色 ,无法将div设置为可见和不可见

不同表的条件API端点Reaction-redux

不协调嵌入图片

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

为什么当雪碧的S在另一个函数中时,Phaser不能加载它?

使用Library chart.js在一个带有两个y轴的图表中绘制两个数据集

如何将对象推送到firestore数组?

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但GET:Object.在Reaction项目中