我有以下代码,它根据 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/