将类添加到父类

发布于 2024-08-14 07:28:57 字数 1005 浏览 2 评论 0原文

HTML:

<div class="tabbed-section">
    <ul class="tabs">
        <li><a href="#tab-1">Tab 1</a><li>
        <li><a href="#tab-2">Tab 2</a><li>
    </ul>
    <div id="tab-1" class="panel">
        content 1
    </div>
    <div id="tab-2" class="panel">
        content 2
    </div>
</div>

jQuery:

    $('.tabbed-section .panel').hide();
    $('.tabbed-section .panel:first').show();
    $('.tabbed-section .tabs li:first').addClass('active');
    $('.tabbed-section .tabs li a').click(function () {
        $('.tabbed-section .tabs li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('.tabbed-section .panel').hide();
        $(currentTab).show();
        return false;
    });

我想将活动选项卡 ID(例如“tab-1”)作为类添加到“tabbed-section”div,并在另一个选项卡处于活动状态时将其删除,我该如何实现这一点?

HTML:

<div class="tabbed-section">
    <ul class="tabs">
        <li><a href="#tab-1">Tab 1</a><li>
        <li><a href="#tab-2">Tab 2</a><li>
    </ul>
    <div id="tab-1" class="panel">
        content 1
    </div>
    <div id="tab-2" class="panel">
        content 2
    </div>
</div>

jQuery:

    $('.tabbed-section .panel').hide();
    $('.tabbed-section .panel:first').show();
    $('.tabbed-section .tabs li:first').addClass('active');
    $('.tabbed-section .tabs li a').click(function () {
        $('.tabbed-section .tabs li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('.tabbed-section .panel').hide();
        $(currentTab).show();
        return false;
    });

I want add the active tab ID ("tab-1" for example) as a class to the "tabbed-section" div, and remove it ofcourse while another tab is active, how do I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉殇 2024-08-21 07:28:57

这应该可以做到,但无法理解为什么要将选项卡 ID 作为类添加到父级:

$('ul.tabs a').click(function() {
    var tab_id = $(this).attr('href');
    $(this)
        .closest('div.tabbed-section')
        .attr('class', 'tabbed-section '+tab_id.replace('#', ''));

    $('.tabbed-section .panel').hide();
    $(tab_id).show();
    return false;
});
$('ul.tabs a:first').click();

This should do it, can't understand why you want to add the tab ID as an class to the parent, though:

$('ul.tabs a').click(function() {
    var tab_id = $(this).attr('href');
    $(this)
        .closest('div.tabbed-section')
        .attr('class', 'tabbed-section '+tab_id.replace('#', ''));

    $('.tabbed-section .panel').hide();
    $(tab_id).show();
    return false;
});
$('ul.tabs a:first').click();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文