通过遍历兄弟姐妹显示父元素内的div

时间:2018-12-06 00:48:59

标签: jquery siblings

在我的WordPress网站中。我的主页上有两个“了解更多”链接。单击任意一个时,我希望他们重新编译上面的相应段落,并将“了解更多”更改为“关闭”。当前单击任一按钮将同时显示这两个按钮。

.hide-mobile {
    display: none;
}

jQuery(document).ready(function($) {
    $(".learnMore").on("click", function(e) {
        var $a = $(this).toggleClass("is-active")
        $a.text(function(i, t) {
            return t === 'Learn More' ? 'Close' : 'Learn More';
        });
        $( "p" ).siblings( ".reveal" ).slideToggle(500);
    });
});

<div class="box-one box">
<h2>Header One</h2>
<p class="hide-mobile reveal">Etiam ut vehicula velit. Cras ut ipsum id tortor ultrices iaculis. Donec sodales ultricies urna vitae porta.</p>
<a class="button" href="/link-url/">Button One</a>
<a class="learnMore mobile">Learn More</a>
</div>

<div class="box-two box">
<h2>Header Two</h2>
<p class="hide-mobile reveal">Morbi et varius elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
<a class="button" href="/link-url-two/">Button Two</a>
<a class="learnMore mobile">Learn More</a>
</div>

1 个答案:

答案 0 :(得分:1)

为什么要从<p>元素开始查找?

$( "p" ).siblings( ".reveal" ).slideToggle(500);

.reveal元素也是您要定位的p时吗?
this是您所需要的!

jQuery(document).ready(function($) {
  $(".learnMore").on("click", function(e) {
    var $a = $(this).toggleClass("is-active")
    $a.text(function(i, t) {
      return t === 'Learn More' ? 'Close' : 'Learn More';
    });
    $( this ).siblings( ".reveal" ).slideToggle(500);
  });
});
.hide-mobile {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box-one box">
  <h2>Header One</h2>
  <p class="hide-mobile reveal">Etiam ut vehicula velit. Cras ut ipsum id tortor ultrices iaculis. Donec sodales ultricies urna vitae porta.</p>
  <a class="button" href="/link-url/">Button One</a>
  <a class="learnMore mobile">Learn More</a>
</div>

<div class="box-two box">
  <h2>Header Two</h2>
  <p class="hide-mobile reveal">Morbi et varius elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
  <a class="button" href="/link-url-two/">Button Two</a>
  <a class="learnMore mobile">Learn More</a>
</div>