jQuery在相同的类之间切换

时间:2014-11-20 08:55:48

标签: javascript jquery html

我有4个应切换的项目。因此,当项目可见时,我点击另一个项目,我点击的项目应该打开。另一个应该关闭。

关于我如何做到这一点的任何建议?

我试图将此添加到我的jQuery文件中,但是没有什么想要切换的话......

var sliderContent = $(this).next('.groupf-more');
        $('.groupf-more').not(sliderContent).hide();
        sliderContent.toggle();

这是我的jQuery:

jQuery(document).ready(function($) {

$('.groupf-more').hide();
$('.groupf-title').toggle(function() {

    $(this).closest('li').find('.groupf-more').slideDown();
    $(this, '.toggle-item').removeClass('groupf-title');
    $(this, '.toggle-item').addClass('groupf-title-active');

    return false;

},
function() {

    $(this).closest('li').find('.groupf-more').slideUp();
    $(this, '.toggle-item').removeClass('groupf-title-active');
    $(this, '.toggle-item').addClass('groupf-title');

    return false;

});
});

这是我的HTML:

<ul class="toggle" style="margin-right: 1%">
    <li class="toggle-item">
        <div class="groupf-title">Title</div>
        <div class="groupf-more">Content</div>
    </li>
    <li class="toggle-item">
        <div class="groupf-title">Title</div>
        <div class="groupf-more">Content</div>
    </li>
</ul>

2 个答案:

答案 0 :(得分:0)

这应该有效:

$('.groupf-more').hide();
$('.groupf-title').click(function() {

    $('.groupf-more').slideUp();
    $(this).closest('li').find('.groupf-more').slideDown();

    return false;

});

答案 1 :(得分:0)

您可以使用

&#13;
&#13;
jQuery(document).ready(function($) {

  var $mores = $('.groupf-more').hide();
  var $items = $('.toggle-item');

  var $titles = $('.groupf-title').click(function() {
    var $more = $(this).next('.groupf-more').slideToggle();
    $mores.not($more).slideUp();
    var $title = $(this).toggleClass('groupf-title groupf-title-active');
    $titles.not($title).removeClass('groupf-title-active').addClass('groupf-title')
    return false;
  });
});
&#13;
.groupf-title {
  color: red;
}
.groupf-title-active {
  color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="toggle" style="margin-right: 1%">
  <li class="toggle-item">
    <div class="groupf-title">Title</div>
    <div class="groupf-more">Content</div>
  </li>
  <li class="toggle-item">
    <div class="groupf-title">Title</div>
    <div class="groupf-more">Content</div>
  </li>
</ul>
&#13;
&#13;
&#13;