javascript - 我的 if else 语句未按预期工作 - 所有语句的innerHTML 保持不变

标签 javascript if-statement conditional-statements innerhtml

我试图找出为什么我的条件语句没有按预期工作。该语句的 else 部分根本不起作用,因为它与 else if 语句相同。我试图简化语句,只使用 if/else,但它不起作用。我非常感谢您提供帮助来解决这个问题。

附注就我而言,如果我想使用 null 语句,我必须将其用作字符串。另一个谜团。

这是我的代码:

var name = prompt("Could you please tell me your name?");
    var newP = document.createElement('p');
    newP.setAttribute('id', 'mainP');
    document.body.appendChild(newP);


    if(name == 'null' || '') {
        newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
    }else if(name == 'Aname' || 'aname') {
        newP.innerHTML = 'Yes, I finally found Aname! ' + String.fromCodePoint(0x1F60D);
    }else {
        newP.innerHTML = "I'm just looking for Aname! " + String.fromCodePoint(0x1F612);
    }

最佳答案

将变量与多个值进行比较时,必须按如下方式进行单独比较:

if(name == 'null' || name == ''){

}

当前,您的 if 语句正在评估与以下语句等效的内容:

if((name == 'null') || ''){

}

关于javascript - 我的 if else 语句未按预期工作 - 所有语句的innerHTML 保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60467649/

相关文章:

javascript - 将类元素恢复为默认值

php - 如果列,行=某些内容,则回显其他内容回显错误

Bash - 在 if 语句中从 crontab -l 读取

python - 以矢量化方式将列添加到 pandas DataFrame 中以其他列值为条件

javascript - 为什么这个CSS类条件在react js中不起作用?

javascript - 如何在移动网络浏览器中访问地理位置

javascript - 通过过滤连接两个数组

javascript - Vue Prop 默认值无法正常工作

c++ - 如何在不使用 goto 的情况下从 if block 跳转到 else block ?

r - 如何使用 data.table 根据条件计算列总和?