jQuery tabs tabs() -显示隐藏独立div取决于tab1 &tab2



我想在tab1被选中时显示特定的div。与tab2相同。请给我一个解决方案,显示/隐藏这些div时,标签被点击。我无法识别处于活动状态的这些选项卡的特定类或Id。我的要求是,当tab1被点击时,我需要显示tab1content1div

链接

http://jsfiddle.net/ucaxt/

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

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.

这种方法确实,但是,要求您在id上附加一个数字,以显示所有内容div元素,以便识别被单击的选项卡,显示的面板和选项卡之外的元素之间的关系;所以你的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>
<br/>
<div id="content1">
    <p>
        on click of first tab (tab1) I need to show this id as well
    </p>
</div>
<br/>
<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 s以略微不同的方式显示/隐藏:

$("#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>
<br/>
<div id="contents">
    <div id="content1">
        <p>
            on click of first tab (tab1) I need to show this id as well
        </p>
    </div>
    <br/>
    <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提琴演示

最新更新