首页 文章

jQuery选项卡tabs() - 显示隐藏单独的div,具体取决于tab1和tab2

提问于
浏览
1

我想在选择tab1时显示特定的div . 与tab2相同 . 单击选项卡时,请给我一个显示/隐藏这些div的解决方案 . 我无法在活动状态下识别这些选项卡的特定类或ID . 我的要求是什么时候点击tab1我需要显示 tab1content1 divs

以下是链接

http://jsfiddle.net/ucaxt/

1 回答

  • 1

    一种不需要将外部内容移动到选项卡本身的方法是:

    var contents = $('div[id^="content"]').hide();
    $("#tabs").tabs({
        activate: function(evt, ui) {
            var num = ui.newPanel.attr('id').replace(/\D+/g, '');
            contents.hide();
            $('#content' + num).show();
        }
    });​
    

    JS Fiddle demo .

    但是,这种方法确实需要在要显示的所有内容 div 元素的 id 中附加一个数字,以便识别单击的选项卡,显示的面板和选项卡外部的元素之间的关系;所以你的HTML变成:

    <div id="tabs">
        <ul>
            <li><a href="#tab1">Tab1</a></li>
            <li><a href="#tab2">Tab2</a></li>
        </ul>
        <div id="tab1">
            test1
        </div>
        <div id="tab2">
            test2
        </div>
    </div>
    
    <div id="content1"> <p> on click of first tab (tab1) I need to show this id as well </p> </div>
    <div id="content2"> <!-- added the '2' to the id here --> <p> on click of Second tab (tab2) I need to show this id as well </p> </div>

    如果您将内容 div 元素包装在外部容器中,在我的演示中它有 idcontainers ,那么您可以将 div 的目标显示/隐藏略有不同:

    $("#tabs").tabs({
        activate: function(evt, ui) {
            var num = ui.newPanel.attr('id').replace(/\D+/g, '');
            $('#contents > div').eq(num - 1).show().siblings().hide();
        }
    });
    

    并使用HTML:

    <div id="tabs">
        <ul>
            <li><a href="#tab1">Tab1</a></li>
            <li><a href="#tab2">Tab2</a></li>
        </ul>
        <div id="tab1">
            test1
        </div>
        <div id="tab2">
            test2
        </div>
    </div>
    
    <div id="contents"> <div id="content1"> <p> on click of first tab (tab1) I need to show this id as well </p> </div>
    <div id="content2"> <p> on click of Second tab (tab2) I need to show this id as well </p> </div> </div>

    JS Fiddle demo .

    我修改了上面的代码,以回应OP留下的评论(下面):

    [On]加载页面我需要显示内容div1以及tab1内容 .

    function showContent(evt, ui) {
        if (!evt || !ui) {
            return false;
        }
        else {
            // ui.newPanel in the activate event,
            // ui.panel in the create event
            var panel = ui.newPanel || ui.panel,
                num = panel.attr('id').replace(/\D+/g, '');
            $('#contents > div').eq(num - 1).show().siblings().hide();
        }
    }
    $(function() {
        $("#tabs").tabs({
            // runs the function when the tabs are created:
            create: function(evt, ui) {
                showContent(evt, ui);
            },
            // runs the function when the tabs are activated:
            activate: function(evt, ui) {
                showContent(evt, ui);
            }
        });
    });​
    

    JS Fiddle demo .

相关问题