Javascript标签和指向标签的直接链接

时间:2014-04-30 16:11:33

标签: javascript html css function tabs

我有一个使用HTML,Javascript和css的标签系统。它工作得很好但是在页面重新加载时,即使#tabname仍在URL的末尾,Tab也会变回第一个。 HTML是

  <body onLoad="init()">
    <h1>E-SPL</h1>

    <ul id="tabs">
      <li><a href="#dash" class="selected">Dashboard</a></li>
      <li><a href="#take">Take</a></li>
      <li><a href="#list">List</a></li>
      <li><a href="#sett">Account Settings</a></li>
    </ul>

    <div class="tabContent" id="dash">
</div>
 <div class="tabContent hide" id="take">
</div>
 <div class="tabContent hide" id="list">
</div>
 <div class="tabContent hide" id="sett">
</div>
</body>

javascript是。              //

    var tabLinks = new Array();
    var contentDivs = new Array();

    function init() {
      // Grab the tab links and content divs from the page
      var tabListItems = document.getElementById('tabs').childNodes;
      for ( var i = 0; i < tabListItems.length; i++ ) {
        if ( tabListItems[i].nodeName == "LI" ) {
          var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
          var id = getHash( tabLink.getAttribute('href') );
          tabLinks[id] = tabLink;
          contentDivs[id] = document.getElementById( id );
        }
      }

      // Assign onclick events to the tab links, and
      // highlight the first tab
      var i = 0;

      for ( var id in tabLinks ) {
        tabLinks[id].onclick = showTab;
        tabLinks[id].onfocus = function() { this.blur() };
        if ( i == 0 ) tabLinks[id].className = 'selected';
        i++;

      }

      // Hide all content divs except the first
      var i = 0;

      for ( var id in contentDivs ) {
        if ( i != 0 ) contentDivs[id].className = 'tabContent hide';
        i++;
      }
    }

    function showTab() {
      var selectedId = getHash( this.getAttribute('href') );

      // Highlight the selected tab, and dim all others.
      // Also show the selected content div, and hide all others.
      for ( var id in contentDivs ) {
        if ( id == selectedId ) {
          tabLinks[id].className = 'selected';
          contentDivs[id].className = 'tabContent';
        } else {
          tabLinks[id].className = '';
          contentDivs[id].className = 'tabContent hide';
        }
      }

      // Stop the browser following the link
      return false;
    }

    function getFirstChildWithTagName( element, tagName ) {
      for ( var i = 0; i < element.childNodes.length; i++ ) {
        if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
      }
    }
    function getHash( url ) {
      var hashPos = url.lastIndexOf ( '#' );
      return url.substring( hashPos + 1 );
    }
    //]]>
    </script>

选项卡完全可以运行,但是当我使用index.php#刷新时,请将URL返回到开头。 我试过添加

if( window.location.hash )
    showTab();

进入init()功能,这不起作用。有什么想法吗?

0 个答案:

没有答案