单击 class 上的函数

Click function on class

如果我想点击 h3 show p,我该如何改进我的脚本 - 但我有更多这些元素,它们在点击时全部打开。有必要给所有h3 id吗?

$('.question h3').click(function(){
$('.question p').toggle();
});

p 元素是 h3 元素的直接下一个兄弟。您可以 .next() 连同点击的元素 jquery 对象来定位相关的 p 元素:

$('.question h3').click(function(){
  $(this).next().toggle();
});

$('.question h3').click(function(){
  $(this).next().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question">
<h3>One</h3>
<p>p - one</p>
<h3>Two</h3>
<p>p - two</p>
<h3>Three</h3>
<p>p - three</p>
</div>

你能不能这样试试:

https://jsfiddle.net/ay6xocLx/1/

 $('.question h3').click(function(){
    $(this).next('p').toggle();
 });

我们通过 $.next() 定位下一个 DOM 元素。

由于 .next() 是出了名的脆弱(只需搜索 SO 以查找“为什么 .next 不起作用”之类的问题),您可以将 h3/p 包裹在另一个 div 中,给出你比 html 布局更灵活。

<div class="question">
    <div class='answer'>
        <h3>One</h3>
        <p>p - one</p>
    </div>
    <div class='answer'>
        <h3>Two</h3>
        <p>p - two</p>
    </div>
    <div class='answer'>
        <h3>Three</h3>
        <hr />
        <p>p - three</p>
    </div>
</div>

然后您可以转到包装器 div 并返回到 p

你会在第 3 季度看到,我添加了 <hr>,然后任何带有 .next().next("p") 的解决方案都会失败。

$('.question h3').click(function(){
    $(this).closest(".answer").find("p").toggle();
});

.next() 的另一种选择。是.nextAll().first(),即:

$('.question h3').click(function(){
    $(this).nextAll("p").first().toggle();
});

这也允许 html 具有更大的灵活性,并且可以与上面添加的 <hr/> 一起使用。