javascript - 使用 jQuery .hide/.show 仅显示和隐藏一个 <div>

标签 javascript jquery html css

.show.hide jQuery 代码适用于每个 <span>同类.q_openq_close .我很清楚我的所有 <div>标签的类别为 .answer所以当我点击任何 <span> 时,它们会显示和隐藏这两个答案.有没有办法只引用一个 <div class=".answer">当点击那个 <span>标记而不是给每个 <div>一个不同的class ?谢谢!

JavaScript 代码:

<script type="text/javascript">
    $(function() {
      $(".q_open").each(function() {
        $(this).click(function() {
          $(".answer").show();
        });
      })
      $(".q_close").each(function() {
        $(this).click(function() {
          $(".answer").hide();
        });
      });
    });
  </script>

HTML代码:

<h2 class="question">
          Q1: (the first question)
          <span class="q_open"></span>
          <span class="q_close"></span>
        </h2>
        <div class="answer" style="display: none;">
          This should only open when clicked by the <span class="q_open"> for Q1.
        </div>
        <h2 class="question">
          Q2: (the second question)
          <span class="q_open"></span>
          <span class="q_close"></span>
        </h2>
        <div class="answer" style="display: none;">
          <p>
           This should only open when clicked by the <span class="q_open"> for Q2.
          </p>
        </div>

最佳答案

我认为您正在寻找某种 Accordion 。为此,您需要定位要打开或关闭的确切 HTML 元素。

试试这个:

$(function() {
  $(".q_open").click(function() {
    // Select the related target to open
    $(this).closest("h2").next(".answer").slideDown();
  });

  $(".q_close").click(function() {
    // Select the related target to close
    $(this).closest("h2").next(".answer").slideUp();
  });
});

这是工作示例:https://jsfiddle.net/ashishanexpert/1xydbj22/

关于javascript - 使用 jQuery .hide/.show 仅显示和隐藏一个 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536587/

相关文章:

javascript - 从多项选择中获取单击选项的索引或值

javascript - flowplayer:如果首先指定 webm,chr​​ome 将不会加载 mp4

javascript - .hover 不适用于我动态分配类的元素

jquery - 如何更好地创建新元素?

html - Angular 9 : Cannot instantiate cyclic dependency

javascript - 如何在 NodeJS 中导入匿名闭包

javascript - 可以通过 JavaScript 在 IE7 中设置选项卡焦点

javascript - DIV 在 html5 视频之上

html - 仅具有绝对定位元素的所见即所得 HTML 编辑器

javascript - 如何自定义 v-for 使用 v-if 在 div 标签中创建一个类