javascript - switch 语句是否最好将选定的类添加到菜单中

标签 javascript

我有一个 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/

相关文章:

javascript - Google map API - 自动完成英国县

javascript - 在选择框中选择下一个元素时遇到问题

javascript - 为什么我在nodejs native 密码中总是得到错误的des-ecb结果?

javascript - JavaScript 中的indexOf 和lastIndexOf

javascript - 基于可区分联合缩小 typescript 泛型类型

javascript - 如何强制浏览器窗口始终位于顶部并处于焦点

javascript - 如何在 Javascript 中更改 HTML 背景颜色 - IE9 问题

javascript - jquery 子菜单 : li items still toggling

javascript - 输入范围 slider 及其指针的自定义

javascript - 我怎样才能写这个javascriptappend();更好的?