简体   繁体   English

if statments(null) 和更改 innerHtml 属性的问题

[英]Issue with if statments(null) and changing innerHtml property

I am messing around trying to learn more JS.我正在努力学习更多的 JS。 I wanted to do a simple if/else statement to get the text of a paragraph to change if a string is empty or not.我想做一个简单的 if/else 语句来让段落的文本在字符串是否为空时发生变化。

The issue is that the statement doesn't execute properly for both cases.问题是该语句在这两种情况下都不能正确执行。 It actually remains the same text that is shown initially.它实际上保持最初显示的相同文本。

Here's my code:这是我的代码:

 <!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>

In the conditional statement if(name == null), null was transformed for some reason to string.在条件语句 if(name == null) 中,由于某种原因将 null 转换为字符串。 If you change the statement to if(name == 'null') it works as intended.如果您将语句更改为 if(name == 'null') 它将按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM