如何在Javascript中没有'else'的情况下编写IF else语句 [英] How to write an IF else statement without 'else' in Javascript

查看:450
本文介绍了如何在Javascript中没有'else'的情况下编写IF else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能在我的脚本中使用 else ;如何在不使用 else 的情况下实现 if else 语句?

I can't use else in my script; how can I implement an if else statement without using else?

我正在尝试调整div的大小:

I'm trying to resize a div:

function hideTable(){
    var table = document.getElementById('PDemo');
    if(table.style.width == "50%") table.style.width = "150px";
    if(table.style.width == "150px") table.style.width = "50%";
}

此脚本不起作用,因为只要第一个如果执行了语句,则第二个 if 语句的条件变为true,因此也会执行,因此没有任何更改。

This script doesn't work because as soon as the first if statement is executed, the condition for the second if statement becomes true, so that executes too, thus nothing changes.

PS这不是作业。我使用的软件只允许使用1行语句。

P.S. This isn't a homework. The software I am using only allows 1-line statements.

推荐答案

如果你不能使用否则(那是疯狂),使用开关

If you can't use an else (and that is crazy), use a switch.

switch (table.style.width) {

    case '50%':
       ...
       break;

    case '150px':
       ...
       break;

}

这篇关于如何在Javascript中没有'else'的情况下编写IF else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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