我有一个嵌套的for循环,它没有完成/退出 它在第二个循环中陷入困境:
for (var j = 0; next.className != "rfccs" && next !== null; j++)
当'next'为空时它才会卡住。
我的代码:
var filtertypes = document.getElementsByClassName("rfccs"); // filtertypes is an array of all filter type headers
var next = null; // placeholder for the next sibling element
var tout = document.getElementById("testout"); //test
tout.innerHTML = "init "; //test
for (var i = 0; i < filtertypes.length; i++) {
filtertypes[i].className += " fhead" + i; // adds a unique class to every filter type header div
var filtertype = filtertypes[i]; // sets filtertype to the current filter type header
next = filtertype.nextElementSibling; // gets the next sibling
for (var j = 0; next.className != "rfccs" && next !== null; j++) { // adds the same class name to all filters in the same filter type
next.className += " ftype" + i;
next.innerHTML += i;
next = next.nextElementSibling;
tout.innerHTML += "i = " + i + "; j = " + j + "///";
if (next == null) {
tout.innerHTML += "DONE";
}
}
tout.innerHTML += "~~~~";
}
我知道我的跟踪/调试代码非常混乱。
以下是Fiddle
答案 0 :(得分:1)
var next = null;
next.className; // TypeError: Cannot read property 'className' of null
在检查null
.className
next !== null && next.className !== "rfccs" // false if null
此外,由于任何 HTMLElement 将由逻辑运算符 truthy ,您可以完全跳过!== null
next && next.className !== "rfccs" // falsy if `next` falsy
答案 1 :(得分:0)
解决方案是
for (var j = 0; next != null && next.className != "rfccs"; j++)
如果next is null
next.className
失败,那么javascript循环
看看这是否符合预期 http://jsfiddle.net/wJBJL/6/