我正在从一个JavaScript数组创建一个数组。我想在选择某些选项时显示一个span。
例如,我想在选择了选项“a”和“c”而没有选择“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>
为什么这不起作用?我怎么才能正确地做呢?
1条答案
按热度按时间ljsrvy3e1#
这个比较逻辑有点破:
字符串
没有
city.value
,因为city
是 * 一个数组 *。你可以检查这个数组 * 是否包含 *this.value
:型
此外,
!"b"
没有多大意义。要检查是否有东西 * 不等于 * 一个值,请使用!=
(或!==
)运算符:型
其结果是:
型