通过URL访问特定选项卡
我在互联网上找到了jQuery中的标签系统,但是制作它(并授权它使用)的人不再可以联系了,所以这就是我在这里提出这个问题的原因。
这是我管理不同标签的javascript代码。
window.onload=function() { // get tab container var container = document.getElementById("tabContainer"); if (document.location.hash.length) { $('.tabs ul li a[href^="' + document.location.hash + '"]').click(); } // set current tab var navitem = container.querySelector(".tabs ul li"); //store which tab we are on var ident = navitem.id.split("_")[1]; navitem.parentNode.setAttribute("data-current",ident); //set current tab with class of activetabheader navitem.setAttribute("class","tabActiveHeader"); //hide two tab contents we don't need var pages = container.querySelectorAll(".tabpage"); for (var i = 1; i < pages.length; i++) { pages[i].style.display="none"; } //this adds click event to tabs var tabs = container.querySelectorAll(".tabs ul li"); for (var i = 0; i < tabs.length; i++) { tabs[i].onclick=displayPage; } } // on click of one of tabs function displayPage() { var current = this.parentNode.getAttribute("data-current"); //remove class of activetabheader and hide old contents document.getElementById("tabHeader_" + current).removeAttribute("class"); document.getElementById("tabpage_" + current).style.display="none"; var ident = this.id.split("_")[1]; //add class of activetabheader to new active tab and show contents this.setAttribute("class","tabActiveHeader"); document.getElementById("tabpage_" + ident).style.display="block"; this.parentNode.setAttribute("data-current",ident); }
这是HTML:
- Les listes
- Les membres
Les listes
Pellentesque habitant morbi tristique senectus...
默认情况下,javascript会加载FIRST选项卡(tabHeader_1,tabpage_1)。 我想要的是,如果我在url example.com/page.php#tabpage_2中举例,它会自动加载第二个标签。
非常感谢你的帮助。
document.location.hash
返回带有数字符号(#hash)的哈希。
你也不能使用.tabs ul li a
作为选择器,因为li
里面没有标签。
尝试使用:
var hash = document.location.hash.substr(1); // skip 1 character (the number sign) $('.tabs ul li[id^="' + hash + '"]').click();
此外,此脚本不在in jQuery
。 它只在整个脚本中使用1个jQuery函数。 我认为这比jQuery更纯粹的JavaScript。