如果您不想使用 jQuery,则不必这样做。这是一个纯javascript版本。请注意,它切换的是一个active
类,而不是一个 ID。
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var myClasses = everyone.className,
otherClasses = favorites.className;
if (myClasses.contains("active"))
{
everyone.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
else {
everyone.className = 'statusOption active';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var myClasses = favorites.className,
otherClasses = everyone.className;
if (myClasses.contains("active"))
{
favorites.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
else {
favorites.className = 'statusOption active';
}
}
function loadXMLDoc(event) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}
编辑以适应评论中的请求:如果您总是希望一个处于活动状态,它会大大缩短代码。这是更新的代码。只需确保everyone
在 HTML 中启动活动类即可
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var otherClasses = favorites.className;
if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var otherClasses = everyone.className;
if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
}
function loadXMLDoc(pageName) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}