Javascript 链接到选项卡

标签 javascript html css tabs hashtag

我有一个完整的选项卡系统,使用以下代码。当您单击 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。我尝试简单地访问该链接,但这没有用...在此先感谢。

最佳答案

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

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

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

关于Javascript 链接到选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23373849/

相关文章:

css - 如何在悬停时向 ngFor 生成的元素添加类?

javascript - Bootstrap 工具提示延迟加载并显示

javascript - 为什么这个递归在 Javascript 上不起作用?

jquery - 获取 span id 并将其作为 href 附加到先前的 span

html - 打印没有页面信息的 HTML 页面

jquery - 使用 jquery 每 3 ul 应用不同的 css 类

javascript - 如果输入之一为空,如何禁用按钮(纯 Javascript)

javascript - 如何将此 Node 代码分解为不同的文件

javascript - 使用ajax刷新div内容

mobile - 有多少移动浏览器支持 CSS 媒体查询?