jquery 在有条件的情况下选择“样式”时更改元素的样式

8mmmxcuj  于 5个月前  发布在  jQuery
关注(0)|答案(1)|浏览(61)

我正在从一个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>

为什么这不起作用?我怎么才能正确地做呢?

ljsrvy3e

ljsrvy3e1#

这个比较逻辑有点破:

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

字符串
没有city.value,因为city是 * 一个数组 *。你可以检查这个数组 * 是否包含 * this.value

city.includes(this.value)


此外,!"b"没有多大意义。要检查是否有东西 * 不等于 * 一个值,请使用!=(或!==)运算符:

this.value != "b"


其结果是:

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

相关问题