【发布时间】:2018-01-22 14:15:13
【问题描述】:
是否可以使用 Jquery 隐藏所有不在数组中的元素?
我在表单上有超过 40 个输入/选择,当我在表单上使用选择时,我想隐藏其中的一些。
$("#type").on('change', function() {
if ($("#type").val() === "Blue") {
var elements = [$("#id-element"), $(".class-element), ... , ... ]; // these elements should be visible and the remaining elements on the form I want to hide them.
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='type'>
<option> Blue </option>
<option> Red </option>
</select>
【问题讨论】:
-
你在这里使用了像id属性这样的名字... $("#type")
-
我更正了。谢谢。
-
不知道需要隐藏哪些元素。提供代表您的基本用例的minimal reproducible example
-
我想隐藏什么元素并不重要。多个类元素和 id。
-
将选择器放入该数组
selectors,而不是jQuery select 语句。然后你可以去$("*").not(selectors.join(',')).hide();,它会解析为$("*").not("#id-element, .class-element, ...").hide();