将 类 切换为 jQuery 中的事件处理程序

Toggle classes with this as an event handler in jQuery

我想在单击与其关联的可折叠 class 按钮时独立切换内容 class。我简要阅读了有关在事件处理程序中使用它的信息。到目前为止,我使用它的方式是切换可折叠的 class(即按钮)。

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <title></title>
  <style>
    .collapsible {
      background-color: #777;
      color: white;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 15px;
    }
    
    .active, .collapsible:hover {
      background-color: #555;
    }
    
    .content {
      padding: 0 18px;
      overflow: hidden;
      display: none;
      background-color: #f1f1f1;
    }
  </style>
  <script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
      $(".collapsible").on("click", function(){
        $(".content").toggle();
      });
    });
  </script>
</head>

<body>
  <button type="button" class="collapsible">Open Section 1</button>
  <div class="content contentDisp">
    <p>Hello There.</p>
  </div>
  <button type="button" class="collapsible">Open Section 2</button>
  <div class="content contentDisp">
    <p>Hello there.</p>
  </div>
  <button type="button" class="collapsible">Open Section 3</button>
  <div class="content contentDisp">
    <p>Hello there.</p>
  </div>

</body>

这接近我想要的,但我不想切换按钮,而是想在单击按钮时切换 div。

<script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
          $(".collapsible").on("click", function(){
            $("this").toggle();
          });
        });
      </script>

您可以通过指定按钮的 class 名称将 thisnext() 结合使用。

$(document).ready(function(){
  $(".collapsible").on("click", function(){
    $(this).next('.content').toggle();
  });
});
    .collapsible {
      background-color: #777;
      color: white;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 15px;
    }
    
    .active, .collapsible:hover {
      background-color: #555;
    }
    
    .content {
      padding: 0 18px;
      overflow: hidden;
      display: none;
      background-color: #f1f1f1;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <button type="button" class="collapsible">Open Section 1</button>
  <div class="content contentDisp">
    <p>Hello There.</p>
  </div>
  <button type="button" class="collapsible">Open Section 2</button>
  <div class="content contentDisp">
    <p>Hello there.</p>
  </div>
  <button type="button" class="collapsible">Open Section 3</button>
  <div class="content contentDisp">
    <p>Hello there.</p>
  </div>

</body>