【问题标题】:Javascript Link to tabsJavascript 链接到选项卡
【发布时间】:2014-06-15 22:23:58
【问题描述】:

我有一个使用以下代码的完整选项卡系统。当您单击 A LI 链接时,它会隐藏其他 div 并显示选定的 div。

<script type="text/javascript">
    //<![CDATA[

    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#hello 时,它将链接到ID 为hello 的div。我尝试简单地访问该链接,但这不起作用...在此先感谢。

【问题讨论】:

  • 不使用getHash() 函数,为什么不使用window.location.hash?此外,您应该在页面加载时调用showTab()。您似乎没有在页面加载后执行它,只有在您单击选项卡时才执行它。

标签: javascript html css tabs hashtag


【解决方案1】:

假设您在页面加载时运行init(),只需在该函数中添加以下内容:

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

当您单击链接以设置正确的选项卡打开时,您会执行函数showTab(),但在页面加载时不会执行,因此它不知道执行您的代码。如果存在哈希位置,则让它运行一次将帮助您获得所需的内容。

【讨论】:

  • init 中的位置。体内的 onLoad 让我兴奋不已。
  • 没关系,只要运行就行了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 2014-03-07
  • 2022-01-22
  • 2020-10-04
  • 1970-01-01
相关资源
最近更新 更多