【问题标题】:Select immediate sibling in CSS or jquery?在 CSS 或 jquery 中选择直接兄弟?
【发布时间】:2017-05-20 19:07:17
【问题描述】:

我在兜圈子,但无法为此找到精确的逻辑。我有以下代码:

<form>
 <table></table>
 <div class="1"> </div>
 <div class="2"> </div>
 <div class="3"> </div>
</form>

表格标签的依赖是通过设置来控制的,它并不总是存在的。如果存在“table”标签,我想要做的是隐藏类 1 的“div”。关于如何通过 CSS 或 Jquery 做到这一点的任何想法?

【问题讨论】:

    标签: jquery css css-selectors jquery-selectors


    【解决方案1】:

    你可以使用+来表示直接兄弟:

    table + div.one {
      display: none;
    }
    <form>
      <table></table>
      <div class="one">a</div>
      <div class="two">b</div>
      <div class="three">c</div>
    </form>

    【讨论】:

    • 无需复制代码块。 Stack Snippets 始终在您的帖子中显示代码。
    【解决方案2】:

    $('table').length &gt; 0 ? $('.class1').hide() : $('.class1').show();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
     <table></table>
     <div class="class1"> 1</div>
     <div class="class2"> 2</div>
     <div class="class3"> 3</div>
    </form>
    1. 假设只存在一个表,使用.length 检查是否存在。
    2. 您可以使用 ID 或类来更具体地检查要检查的表。
    3. 不要使用数字开始命名类

    具体表:

    $('table#check').length &gt; 0 ? $('.class1').hide() : $('.class1').show();//checks for table with id check if present then do hide or show 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <table id='check'></table>
      <div class="class1">1</div>
      <div class="class2">2</div>
      <div class="class3">3</div>
      <table id='check1'></table>
    </form>

    【讨论】:

      【解决方案3】:

      Working Fiddle

      使用.siblings() 方法。

      if ($('table').length > 0) {
        $("table").siblings().first().hide();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        相关资源
        最近更新 更多