简体   繁体   English

javascript undefined nodelist返回true

[英]javascript undefined nodelist returns true

I have two sets of divs. 我有两组div。 Fist set is assigned classname tD , while the other has a class tU . 第一个拳头被分配了类名tD ,而另一个拳头被分配了类tU tD / tU could be undefined. tD / tU可能不确定。 In cases where tU is undefined, tD !== null returns true in chrome. 在未定义tU情况下, tD !== null在chrome中返回true。 It actually returns []. 它实际上返回[]。 Why is this happening? 为什么会这样呢?

var tD = document.getElementsByClassName("t-d"); // undefined
var tDLength = tD.length;
var tU = document.getElementsByClassName("tU"); //defined
var tULength = tU.length;

while (tU !== null && triangle_up_length > 0) {
        tU[tULength - 1].style.borderLeftWidth = 128 + "px";
        tU[tULength - 1].style.borderRightWidth = 128 + "px";
        tULength--;
}
while (tD !== null && triangle_down_length > 0) {
    tD[tDLength - 1].style.borderLeftWidth = 128 + "px";
    tD[tDLength - 1].style.borderRightWidth = 128 + "px";
    tULength--;
}

while (tU.length > 0) will do what you want. while (tU.length > 0)会做你想要的。

document.getElementsByClassName returns an empty nodelist (almost array), if nothing is found, so you shouldn't check for null . document.getElementsByClassName返回空的节点列表(几乎是数组),如果什么也没找到,那么您不应该检查null

Compete reedit: 竞争编辑:

if( tU ) {
   if( tU.length > 0 ) {
      //do the stuff
   }
{

This is the standard behavior of GetElementByClassName 这是GetElementByClassName的标准行为

"..Returns an array-like object of all child elements which have all of the given class names..". “ ..返回具有所有给定类名称的所有子元素的类似数组的对象。” Then you must check for 然后,您必须检查

 if( tD.length != 0 ){}  

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

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