切换除单击的子元素之外的所有元素

Toggle all elements except the sub element of clicked one

本文关键字:元素 单击      更新时间:2023-09-26

我需要切换(显示/隐藏)<p>,这是点击<li>的子元素,而所有其他<p>都应该隐藏。我能够做到这一点。

但是单击相同的元素(现在显示)不会隐藏。如何实现这一点?

$(document).ready(function(){
    $("p").hide();
    $("li").click(function(){
        $("p").not(this).hide(200);
        $("p", this).toggle(200);
    });
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<ul>
  <li><a>q1</a>
    <p>a1</p>
  </li>
  <li><a>q2</a>
    <p>a3</p>
  </li>
  <li><a>q3</a>
    <p>a3</p>
  </li>
  <li><a>q4</a>
    <p>a4</p>
  </li>
</ul>
</body>
</html>

您需要将

要排除的p元素传递给not(),您现在正在传递this它指的是li元素

$(document).ready(function() {
  $("p").hide();
  $("li").click(function() {
    var $ps = $("p", this).stop(true).toggle(200);
    $("p").not($ps).stop(true).hide(200);
  });
});
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
  <ul>
    <li><a>q1</a>
      <p>a1</p>
    </li>
    <li><a>q2</a>
      <p>a3</p>
    </li>
    <li><a>q3</a>
      <p>a3</p>
    </li>
    <li><a>q4</a>
      <p>a4</p>
    </li>
  </ul>
</body>
</html>

$(document).ready(function(){
    $("p").hide();
    $("li").click(function(){
        $(this).find('p').toggle(200);
        $(this).siblings('p').hide(200);
    });
});

演示尝试这样做

使用这个简单的逻辑:

$(document).ready(function(){
    $("p").hide();
    $("li").click(function(){
        $("p").not(this).hide(200);
       if($("p",this).is(":visible")){
        $("p", this).hide(200);}
       else{
       $("p", this).show(200);}
    });
});

检查这个小提琴

像这样更改 jQuery 代码

$(document).ready(function(){
    $("p").hide();
    $("li").click(function(){
        $("p").not($(this).find("p")).hide(200);
        $(this).find("p").toggle(200);
    });
});