我有一个 userControl.htm,其中包含页面的导航链接,我有带有 ID 的页面,并且我想将“选定”类广告到相应的主页链接。
我认为 var page = (getElementByID("someId")) 会做到这一点,但没有运气。
var page = (getElementByID("someId"))
switch (page) {
case 'home':
document.getElementById("About").className = "selected";
break;
case 'about':
document.getElementById("About").className = "selected";
break;
case 'contact':
document.getElementById("contact").className = "selected";
break;
case 'services':
document.getElementById("services").className = "selected";
break;
default:
document.getElementById("home").className = "selected";
}
谢谢
最佳答案
考虑使用键值映射而不是编写冗余代码:
//value with corresponding, and maybe not 1:1 pair
var pairs = {
'home' : 'About',
'about' : 'About',
'contact' : 'contact',
'services' : 'services',
'default' : 'home'
//you can add as much as you want here
};
//then get your page value
var page = getYourValue();
//page might or might not exist on the pairs list, thus we check
//default to 'default' if non-existent
page = (pairs[page]) ? page : 'default';
//then get from the map the desired value
document.getElementById(pairs[page]).className = "selected";
您可以使用以下任一方式获取正文的 ID:
document.body.id
//or
document.getElementsByTagName('body')[0].id
关于javascript - switch 语句是否最好将选定的类添加到菜单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14793962/