【问题标题】:jQuery toggle between same classesjQuery 在相同的类之间切换
【发布时间】:2015-01-18 01:32:54
【问题描述】:

我有 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>

【问题讨论】:

  • 您使用的是什么版本的 jQuery? jQuery 1.9 中删除了.toggle 的双函数形式。
  • 您可以使用活动课程(您已经在做 - 但不要删除 groupf-title,只需添加活动课程作为第二个课程)。当点击一个项目时,你给它一个活跃的类。然后您循环浏览所有项目并关闭所有没有活动类的项目。
  • $(this, '.toggle-item') 应该做什么?
  • @barmar:我认为 1.9 以上... jQuery 不是我的菜,我一直在测试。除了 div 之间的切换之外,一切都与该脚本一起工作。感谢您到目前为止的回复!

标签: javascript jquery html


【解决方案1】:

你可以使用

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;
  });
});
.groupf-title {
  color: red;
}
.groupf-title-active {
  color: green;
}
<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>

【讨论】:

  • 虽然,我的课程错了,但这个切换有效!谢谢! :)
【解决方案2】:

这应该可行:

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

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

    return false;

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-08-09
    • 2012-06-22
    相关资源
    最近更新 更多