此脚本在文本区域上方创建菜单选项卡。如果在一个页面上只使用一次该脚本就可以工作,但是我需要在一个页面上使用它两次,以创建 2 个文本区域,每个文本区域上方都有一个菜单。一旦我使用它两次,只有一个实例可以工作。有什么建议。
window.onload=function() {
// get tab container
var container = document.getElementById("tabContainer");
// 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);
}
最佳答案
还没有找到解决方案,但仅供引用,您最初将其标记为 jQuery,如果它是 jquery,您可以轻松地破坏该代码的几行并将其编写为简单的:(取决于版本)
function displayPage(e) {
var current = $(this).parent().attr("data-current");
$("#tabHeader_" + current).removeClass("tabActiveHeader")
$("#tabpage_" + current).hide();
var ident = this.id.split("_")[1];
$(this).addClass("tabActiveHeader");
$("#tabpage_" + ident).show();
$(this).parent().attr({ 'data-current': ident })
}
$(function() {
var container = $("#tabContainer"),
navitem = container.find((".tabs ul li")).first(),
ident = navitem[0].id.split("_")[1];
navitem.addClass("tabActiveHeader").parent().attr({ 'data-current': ident });
$(".tabpage").filter(function(i) { return i>0; }).hide();
// OR
// $(".tabpage:not(:first-child)").hide();
$(".tabs ul li").on("click", displayPage)
});
See WORKING Example of the previous jQUERY in this jsFiddle
另外,你看过jQueryUI.Tabs吗? ?
关于javascript - 当在单个页面上使用此 .js 两次时,它仅在一个实例中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306310/