简体   繁体   English

为什么 if 在我改变条件后返回 true?

[英]Why if returns true after i change condition?

In html i have this:在 html 我有这个:

<div class="MyClass" id="1" onclick="functionX()">  </div>
<div class="MyClass" id="2" onclick="functionX()">  </div>

And my script:还有我的剧本:

functionX() {
  if (document.getElementById("1").hasAttribute("onclick")) {
    window.onclick = e => {
      document.getElementById(e.target.id).appendChild(document.createElement("div", {
        class: "someClass"
      }));
    }
  }
}

if (document.getElementById("1").contains(document.getElementById("1").querySelector("[class='someClass']"))) 
{
  let foo = document.getElementsByClassName('myClass');
  for (let i = 0; i < foo.length; i++) 
  {
    foo[i].removeAttribute("onclick");
  }
}

When i click on the div which no longer has an attribute "onclick" the condition from the functionX continues to execute.当我单击不再具有属性“onclick”的 div 时,functionX 的条件继续执行。

The thing is you're removing an attribute.问题是你要删除一个属性。 Removing the attribute does nothing to remove the event handler.删除属性不会删除事件处理程序。 You need to detach the handler.您需要分离处理程序。

The if is not part of the function. if 不是 function 的一部分。

functionX() {
  if (document.getElementById("1").hasAttribute("onclick")) {
    window.onclick = e => {
      document.getElementById(e.target.id).appendChild(document.createElement("div", {
        class: "someClass"
      }));
    }
  }
}  // end of function


// not in fuction    
if (document.getElementById("1").contains(document.getElementById("1").querySelector("[class='someClass']"))) {
  let foo = document.getElementsByClassName('myClass');
  for (let i = 0; i < foo.length; i++) {
    foo[i].removeAttribute("onclick");
  }
}

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

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