简体   繁体   English

其他运算符 | JS | 镀铬扩展

[英]else operator | JS | Chrome extention

I have this function:我有这个 function:

function FizzBuzz(){
   if(document.getElementById("textbox") == true){
      Fizz();
   } else {
      Buzz();
   }
}

The Fizz() and Buzz() functions place text in textboxes specified by document.getElementById in their own functions. Fizz()Buzz()函数将文本放置在由document.getElementById在它们自己的函数中指定的文本框中。

in it's current configuration, it should to my understanding execute Fizz() if ("textbox") is found on the webpage, otherwise Buzz() should be executed.在它的当前配置中,据我了解,如果在网页上找到("textbox") ,则应该执行Fizz() ,否则应该执行Buzz() This does not happen, and it will only execute one of them, no matter if ("textbox") is true or not.这不会发生,它只会执行其中一个,无论("textbox")是否为真。

The ("textbox") referenced above only exists on one of the two pages this is designed to work with.上面引用的("textbox")仅存在于设计用于使用的两个页面之一上。

Changing to !== true will invert the effect, the same with == false , as with the current behavior is expected.更改为!== true将反转效果,与== false相同,与预期的当前行为一样。 I have also tried to check for == null and !== null , this results in the same behavior.我还尝试检查== null!== null ,这会导致相同的行为。

I simply do not understand what I'm doing wrong here.我根本不明白我在这里做错了什么。

document.getElementById returns either null or element. document.getElementById 返回 null 或元素。 So, comapring both with == or === with true or false will always return false.因此,将 == 或 === 与 true 或 false 一起映射将始终返回 false。 You can directly put document.createElement inside if as a condition.您可以直接将 document.createElement 放入 if 作为条件。 If you still face the issue, I suggest you to put a break point and see how the code is executed.如果还是遇到这个问题,我建议你下一个断点,看看代码是如何执行的。

Sample code for better understanding - https://codepen.io/Yash__/pen/WNzgYvL?editors=1111更好理解的示例代码 - https://codepen.io/Yash__/pen/WNzgYvL?editors=1111

<h1 id="hai">hai</h1>

if(document.getElementById('hai')){
  console.log("there");
}else{
  console.log("not there")
}

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

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