在javascript中替代if,else if,else if,else if等 [英] Alternative to if, else if, else if, else if, etc in javascript

查看:388
本文介绍了在javascript中替代if,else if,else if,else if等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,这取决于url参数更改,然后在窗体上隐藏选择选项。即www.example.com?type=images

I've got the following code which depending on a url parameter changes and then hides a select option on a form. ie www.example.com?type=images

最终会有超过20个不同的参数。我想知道一个更好的方法,而不是拥有大量的elses。只是概述了如何做到这一点很好,我是新手,所以我希望能够得到答案并从中学习。谢谢。

Eventually there will be over 20 different parameters. I'd like to know of a better way than having a huge amount of if elses. Just an outline of how to do it is fine, I'm new to this, so I'd like to be able to take the answer and learn from it. Thanks.

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";
}


推荐答案

为了不重复代码,我用这样的代码编写你的代码,索引号为查找表,每个选项没有重复的代码:

In the interest of not repeating code, I'd write your code like this with a lookup table for the index num and no repeated code for each option:

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中替代if,else if,else if,else if等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆