【问题标题】:Issue with if statments(null) and changing innerHtml propertyif statements(null) 和更改 innerHtml 属性的问题
【发布时间】:2020-06-12 13:59:58
【问题描述】:

我正在四处寻找更多的 JS。如果字符串为空,我想做一个简单的 if/else 语句来更改段落的文本。

问题在于该语句在这两种情况下都不能正确执行。它实际上与最初显示的文本相同。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Time to practice: Adding elements with Javascript</title>
</head>
<body>

  <main>
    
  </main>

  <script>
    document.body.style.cssText = 'height: 100vw; width: 100vw';
    var main = document.body.children[0].style.cssText = 'background-color: white; height: 100vw; width: 100vw';
    var style = document.createElement('style');
    style.innerHTML = `
      #mainP {
        font-size: 100px;
      }`
    ;
    document.head.appendChild(style);

    var name = prompt("What's your name?");
    var newP = document.createElement('p');
    newP.setAttribute('id', 'mainP');
    document.body.children[0].appendChild(newP);
    
    console.log(name);

    if (name === null) {
      document.getElementById('mainP').innerHTML = "I didn't even want to know your name ";
    } else {
      document.getElementById('mainP').innerHTML = 'Hello ' + name + '.' + ' Hope you are having an awesome day!';
    }
  </script>
  
</body>
</html>

【问题讨论】:

  • Drew 您声明如果 name 为空字符串但您正在检查 null,您想要执行 x。要检查空字符串,您可以将 null 更改为 ""。
  • 这里一个简单的解决方案是使用松散比较,这将涵盖两种情况,空字符串和null,但不会因任何实际值而失败。
  • 感谢大家的建议。不幸的是,它们都不适用于我的情况。我真的不知道问题是什么。从逻辑上讲,它应该工作,但它没有。
  • 我在一位朋友的帮助下最终解决了这个问题。我不知道为什么,但为了让它按预期工作,我必须做 if(name == 'null')。我们试图弄清楚为什么脚本只会以 null 作为字符串运行,但我们没有得出任何结论。

标签: javascript jquery html dom conditional-statements


【解决方案1】:

在条件语句 if(name == null) 中,null 由于某种原因被转换为字符串。如果您将语句更改为 if(name == 'null') 它会按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多