使我的jquery选项卡式浏览更加智能

Smarten up my jquery tabbed browsing

本文关键字:浏览 智能 我的 jquery 选项      更新时间:2023-09-26

我整理了一个非常简单的选项卡式浏览器,你可以在这里看到http://jsfiddle.net/zandergrin/sN2Eu/

我只是想知道是否有办法使脚本更智能,以便自动处理所有编号 - 即我可以添加一个新选项卡,而不需要添加新的 javascript。

我知道我可以用jquery ui做到这一点,但是a)我正在努力保持它的超轻量级,更重要的是,b)我正在努力学习!!

谢谢 - 我对我的 javascript 非常基本,所以任何解释将不胜感激

您需要

为每个选项卡添加一个 comman 类,以便您可以选择所有选项卡和一个唯一的 id,该 id 也是链接href中的值。还要为所有链接添加一个公共类。

<div class="tab-nav">
     <ul>
         <li><a href="#tab1" class="tabclick active">Overview</a></li>
         <li><a href="#tab2" class="tabclick">Specs</a></li>
         <li><a href="#tab3" class="tabclick">More Info</a></li>
     </ul>
</div>

<div id="tab1" class="tab">
    <p>content1</p>
</div>
<div id="tab2" class="tab" style="display: none">
    <p>content2</p>
</div>
<div id="tab3" class="tab" style="display: none">
    <p>content3</p>
</div>

你的JavaScript现在可以

function tabActions(e) {
    // e.preventDefault(); // stop default browser action of link will not add the hash to the url
    var targetId = $(this).attr('href'); // extract the value in the href (the #tab1 for example)
    $('.tabclick').removeClass('active'); // remove the active class from all links (find them by their common class)
    $(this).addClass('active'); // add it to the currently clicked link
    $('.tab').hide(); // find all tabs (by the common class) and hide them
    $(targetId).show(); // show the current tab 
};
$('.tabclick')
    .click(tabActions) // bind handler
    .filter(function(){ // find the link that points to the hash in the url
        return this.hash == window.location.hash;
    })
    .click(); // manually trigger click on it

http://jsfiddle.net/gaby/sN2Eu/3/演示