javascript - 在javascript中替代if,else if,else if,else if等

标签 javascript switch-statement if-statement

我有以下代码,它根据 url 参数更改,然后隐藏表单上的选择选项。即 www.example.com?type=images

最终会有 20 多个不同的参数。我想知道比拥有大量 if else 更好的方法。只是概述如何做就可以了,我是新手,所以我希望能够得到答案并从中学习。谢谢。

var type = getURLparameter('type'); //from another function

if (type == "images"){
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[1].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}
else if (type == "pizza") {
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[2].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}
else (type == "cheese") {
    var selectDiv =('divid');
    var selectField = ('selectid');
    document.getElementById(selectField).options[3].selected=true;
    document.getElementById(selectDiv).style.visibility="hidden";
}

最佳答案

为了不重复代码,我会像这样编写您的代码,使用索引号的查找表并且每个选项都没有重复的代码:

var typeNum = {
    images: 1,
    pizza: 2,
    cheese: 3
};

var type = getURLparameter('type');

if (type in typeNum) {
    document.getElementById('selectid').options[typeNum[type]].selected = true;
    document.getElementById('divid').style.visibility = "hidden";
}

关于javascript - 在javascript中替代if,else if,else if,else if等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8304632/

相关文章:

java - 打开点击按钮

c - C 中的十进制值被认为是真的吗?

javascript - 单击 onclick 单元格滚动到顶部

javascript - 如何使用 spyOn 测试异步函数?

class - 带类的Clojure案例陈述

php - setter/getter 中重复开关的设计模式?

python文件逐行读取并检查条件,如果不为真则等待其为真而不跳过该行

javascript - 如何将现有文本片段放入新创建的元素节点中?

javascript - 使按钮组动态化

java - 带字符串 Java 的 Switch Case