jQuery移动导航选项卡

Mat*_*teo 15 javascript jquery tabs navbar jquery-mobile

我希望在我的jQuery Mobile项目中有一个标签导航.我知道我可以使用数据角色'navbar'但我只想更改导航栏下面的内容而不刷新到新页面.到目前为止,我只能有几个不同的页面,相同的导航栏相互链接,但这不是我想要的.

谁能帮我?

先感谢您

Jas*_*per 32

您可以使用jQuery Mobile导航栏样式,但使用您自己的点击处理程序,而不是更改页面,点击将只隐藏/显示同一页面上的正确内容.

HTML

<div data-role="navbar">
    <ul>
        <li><a href="#" data-href="a">One</a></li>
        <li><a href="#" data-href="b">Two</a></li>
    </ul>
</div><!-- /navbar -->
<div class="content_div">onLoad Content</div>
<div id="a" class="content_div">Some 'A' Content</div>
<div id="b" class="content_div">Some 'B' Content</div>
Run Code Online (Sandbox Code Playgroud)

JAVASCRIPT

$(document).delegate('[data-role="navbar"] a', 'click', function () {
    $(this).addClass('ui-btn-active');
    $('.content_div').hide();
    $('#' + $(this).attr('data-href')).show();
    return false;//stop default behavior of link
});
Run Code Online (Sandbox Code Playgroud)

CSS

.content_div {
    display: none;
}
.content_div:first-child {
    display: block;
}
Run Code Online (Sandbox Code Playgroud)

这是上面代码的jsfiddle:http://jsfiddle.net/3RJuX/

注意:

  • 导航栏中的每个链接都有一个"data-href"属性,该属性设置为将显示的div(或您要使用的任何容器)的id.

更新

1年后,我回到这个答案,并注意到委托事件处理程序选择器可以优化一点,以利用类而不是属性(这比查找快得多):

$(document).delegate('.ui-navbar a', 'click', function () {
    $(this).addClass('ui-btn-active');
    $('.content_div').hide();
    $('#' + $(this).attr('data-href')).show();
});
Run Code Online (Sandbox Code Playgroud)

更新

通过使用相对选择器而不是绝对选择器,可以使此代码更加模块化(例如$('.content_div'),因为这将选择DOM中的所有匹配元素,而不是仅选择相对于单击按钮的元素).

//same selector here
$(document).delegate('.ui-navbar ul li > a', 'click', function () {

    //un-highlight and highlight only the buttons in the same navbar widget
    $(this).closest('.ui-navbar').find('a').removeClass('ui-navbar-btn-active');

    //this bit is the same, you could chain it off of the last call by using two `.end()`s
    $(this).addClass('ui-navbar-btn-active');

    //this starts the same but then only selects the sibling `.content_div` elements to hide rather than all in the DOM
    $('#' + $(this).attr('data-href')).show().siblings('.content_div').hide();
});?
Run Code Online (Sandbox Code Playgroud)

这允许您在页面或伪页面上嵌套选项卡和/或具有多组选项卡.

使用的"相对选择器"的一些文档:

这是一个例子:http://jsfiddle.net/Cfbjv/25/(现在离线)