【问题标题】:Jquery hide all elements that are not in arrayjQuery隐藏所有不在数组中的元素
【发布时间】: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();

标签: jquery html forms input


【解决方案1】:

你可以使用jquery的not

$("#type").on('change', function() {
  if ($(this).val() === "Blue") {
  
  //note that this is a single string with comma sepreating between different selectors
    var elements = "#id-element,.class-element";

    //select all inputs
    $("input").not(elements).hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='type'>
        <option> select one </option>
        <option> Blue </option>
        <option> Red </option>
</select>
<br />
<input id="id-element" value="#id-element" /><br />
<input class="class-element" value=".class-element" /><br />
<input id="other-id" value="#other-id" /><br />
<input class="other-class" value=".other-class" /><br />

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 2015-08-23
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2012-02-03
    相关资源
    最近更新 更多