javascript 中的多个 IF 和 ELSE IF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3233506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:46:43  来源:igfitidea点击:

Multiple IF's and ELSE IF's in javascript

javascriptarraysradio-buttonpushif-statement

提问by IceDragon

So what's getting pushed to this array is dependant on a few radio boxes. I've got this for standard and wheelchair seats:

因此,推送到该阵列的内容取决于几个无线电盒。我为标准座位和轮椅座位准备了这个:

if(document.getElementById('standardseat').checked) {
  //Standard seat is checked
seatsArray.push(e.posX, e.posY);
}
else if(document.getElementById('wheelchairseat').checked) {
  //Wheelchair seat is checked
seatsArray.push("Wheelchair " + e.posX, e.posY);
}

And this is the equivalent form code:

这是等效的表单代码:

<input id="standardseat" type="radio" name="seat" value="standard" /> Standard seat
<input id="wheelchairseat" type="radio" name="seat" value="wheelchair" /> Wheelchair seat

But I want to add in some more radio boxes, which are separate from the standard/wheelchair seat:

但我想添加更多的收音机盒,它们与标准/轮椅座椅分开:

<input id="backnave" type="radio" name="area" value="backnave" /> Back Nave
<input id="frontnave" type="radio" name="area" value="frontnave" /> Front nave
<input id="middlenave" type="radio" name="area" value="middlenave" /> Middle nave

And I want the push to also include this. To explain, if the user ticked "Wheelchair seat" and "Middle nave", the push should output ("MN, Wheelchair " + e.posX, e.posY). Is there any way of making this happen without manually including a lot of else if's for each possible outcome (I may even want to add a third set of radio boxes)?

我希望推动也包括这一点。解释一下,如果用户勾选了“轮椅座位”和“中殿”,则推送应该输出(“MN, Wheelchair” + e.posX, e.posY)。是否有任何方法可以在不为每个可能的结果手动包含很多 else if 的情况下实现这一点(我什至可能想添加第三组单选框)?

Thanks!

谢谢!

回答by Jeffrey Blake

I would build up the string that describes the chair with a comparatively small number of ifstatements, and then call the pushat the end.

我会用相对较少的if语句来构建描述椅子的字符串,然后push在最后调用。

So something like:

所以像:

var desc = "";
if(document.getElementById('wheelchairseat').checked) {
  //Wheelchair seat is checked
  desc = "Wheelchair "+desc;
}

if(document.getElementById("backnave").checked) {
  desc = "BN, "+desc;
} else if(document.getElementById("middlenave").checked) {
  desc = "MN, "+desc;
} else if(document.getElementById("frontnave").checked) {
  desc = "FN, "+desc;
}

seatsArray.push(desc + e.posX, e.posY);

This can easily be extended to account for additional groups of blocks.

这可以很容易地扩展到考虑额外的块组。

回答by Mark Eirich

You are right, IceDragon, it doesn't make sense to use multiple if/else's, because every single time you add options, you'll have to rewrite your code. There are a number of ways to avoid this. Here is just one approach:

你是对的,IceDragon,使用多个 if/else 是没有意义的,因为每次添加选项时,你都必须重写代码。有很多方法可以避免这种情况。这里只是一种方法:

<html><body>
  <form>
    <p>
      <input type="radio" name="seat" onclick="chose(this, 'Standard')" /> Standard seat
      <input type="radio" name="seat" onclick="chose(this, 'Wheelchair')" /> Wheelchair seat
    </p><p>
      <input type="radio" name="area" onclick="chose(this, 'BN')" /> Back Nave
      <input type="radio" name="area" onclick="chose(this, 'FN')" /> Front nave
      <input type="radio" name="area" onclick="chose(this, 'MN')" /> Middle nave
    </p>
  </form>
  <script>
    // make sure to put these in the order you wish them to appear in the output
    var selections = { area: '', seat: '' };
    var seatsArray = [];
    function chose(input, value) {
      selections[input.name] = value;
    }
    // call this function when user clicks the floor plan:
    function image_clicked(e) {
      var desc = [];
      for (var i in selections) if (selections[i] != '') desc.push(selections[i]);
      seatsArray.push(desc.join(', ') + ' ' + e.posX, e.posY);
    }
  </script>
</body></html>

Notice that in the selectionsobject, we're keeping track of the selections that the user has made so far. Then when the user clicks the image (or whatever triggers the code you are working on), the function simply formats the values already collected.

请注意,在selections对象中,我们正在跟踪用户迄今为止所做的选择。然后,当用户单击图像(或任何触发您正在处理的代码的东西)时,该函数只需格式化已收集的值。

The one drawback to the way I have written this code is that browsers tend to cache the state of the radio buttons, so a radio button may be already selected, but the chose() function wasn't called. One quick and dirty workaround is to add an ID to the form tag and run this on page load:

我编写此代码的方式的一个缺点是浏览器倾向于缓存单选按钮的状态,因此可能已经选择了单选按钮,但没有调用 selected() 函数。一种快速而肮脏的解决方法是向表单标签添加一个 ID 并在页面加载时运行它:

document.getElementById('form').reset();

Where 'form' is the ID attribute of the form tag.

其中 'form' 是表单标签的 ID 属性。

回答by George Marian

Generally speaking, when you have a lot of if/else-if's, you consider replacing them with a switch/case statement.

一般来说,当你有很多 if/else-if 时,你可以考虑用 switch/case 语句替换它们。

http://www.javascriptkit.com/javatutors/switch.shtml

http://www.javascriptkit.com/javatutors/switch.shtml

Now, this wouldn't necessarily be appropriate for your situation, as the type of seat is a separate condition from its position (front/middle/back).

现在,这不一定适合您的情况,因为座椅的类型与其位置(前/中/后)不同。

There may be a more elegant approach than your code, but I'm not completely understanding the context. What are you doing with this array?

可能有比您的代码更优雅的方法,但我并不完全了解上下文。你用这个数组做什么?

回答by jasongetsdown

Make the valuewhat you want to appear in the result string. If you want 'MN' make the value'MN'.

使value您想要出现在结果字符串中的内容。如果您想要“MN”,请制作value“MN”。

Then instead of writing an ifstatement for each possible state you could loop through the inputobjects to find the one that is checked.

然后,if您可以循环遍历input对象以找到被检查的对象,而不是为每个可能的状态编写语句。

Get all the inputs from each for like so...

像这样从每个人那里获取所有输入......

var chairFormElems = document.getElementById('chairFormId').elements;
var naveFormElems = document.getElementById('naveFormId').elements;

Then loop through each and find the one that's checked. Then just concat the valueattributes to make your result string.

然后循环遍历每个并找到已检查的那个。然后只需连接value属性即可生成结果字符串。