jQuery-转换为可在一页上使用多个选项卡吗? [英] Jquery - convert to work with multiple tabs on one page?

查看:36
本文介绍了jQuery-转换为可在一页上使用多个选项卡吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码进行简单的jQuery标签设置:

I'm using this code for a simple jQuery tab setup:

$('.tabs .tab_content').hide(); // Hide all divs
$('.tabs .tab_content:first').show(); // Show the first div
$('.tabs ul.tab_nav li:first').addClass('current_tab'); // Set the class of the first link to active

$('.tabs ul.tab_nav li a').click(function(){ //When any link is clicked
    $('.tabs ul.tab_nav li a').removeClass('current_tab'); // Remove active class from all links
    $(this).addClass('current_tab'); //Set clicked link class to active

    var currentTab = $(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link

    $('.tabs .tab_content').hide(); // Hide all divs
    $(currentTab).show(); // Show div with id equal to variable currentTab
    return false;
});

这是示例HTML:

<div class="box tabs">
                    <div class="box_header">
    <h2>3/4 Width</h2>
    <ul class="tab_nav">
        <li><a href="#tab1" class="current_tab">Tab #1</a></li>
        <li><a href="#tab2">Tab #2</a></li>
        <li><a href="#tab3">Tab #3</a></li>
        <li><a href="#tab4">Tab #4</a></li>
    </ul>
</div>
<div class="box_content tab_content" id="tab1">1</div>
<div class="box_content tab_content" id="tab2">2</div>
<div class="box_content tab_content" id="tab3">3</div>
<div class="box_content tab_content" id="tab4">4</div>
</div>

对于一组选项卡来说效果很好,但是如果我添加另一组选项卡(即上面的另一段代码),一切都搞砸了-它会将选项卡视为一个大对象,而不是两个单独的选项卡实例.我如何转换它使其起作用?理想情况下,不向HTML添加太多/任何内容?

It works beautifully for one set of tabs, but if I add another set (i.e., another block of code as above) it all messes up - it treats the tabs as one big object, not two seperate tab instances. How can I convert it so that it will work? Ideally without adding much/anything to the HTML?

谢谢!

亚历克斯

推荐答案

尝试此代码

$('.tabs').each(function(){
var tab = $(this);
tab.find('.tab_content').hide(); // Hide all divs
tab.find('.tab_content:first').show(); // Show the first div
tab.find('ul.tab_nav li:first').addClass('current_tab'); // Set the class of the first link to active

tab.find('ul.tab_nav li a').click(function(){ //When any link is clicked
    tab.find('ul.tab_nav li a').removeClass('current_tab'); // Remove active class from all links
    tab.addClass('current_tab'); //Set clicked link class to active

    var currentTab = tab.find($(this).attr('href')); // Set variable currentTab to value of href attribute of clicked link

    tab.find('.tab_content').hide(); // Hide all divs
    $(currentTab).show(); // Show div with id equal to variable currentTab
    return false;
});
})

这篇关于jQuery-转换为可在一页上使用多个选项卡吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆