Javascript 而循环将永远持续下去
我有一段时间保持运行,即使满足条件,即Javascript 而循环将永远持续下去,javascript,algorithm,while-loop,Javascript,Algorithm,While Loop,我有一段时间保持运行,即使满足条件,即el.tagName!='H2' 我不知道为什么它在找到最接近的标题(在本例中是H2)后仍在运行。您可以在此处查看代码PN 在您的代码笔中,您永远不会调用GrabClosesHeader()。您正在调用closesHeader()(它不存在)。打字错误将其更改为对grabsclosesHeader()的函数调用会记录所有元素,直到崩溃,因为它不再有父元素。任何地方都没有无限循环的迹象。 function grabClosestHeader (el) {
el.tagName!='H2'
我不知道为什么它在找到最接近的标题(在本例中是H2)后仍在运行。您可以在此处查看代码PN
在您的代码笔中,您永远不会调用
GrabClosesHeader()
。您正在调用closesHeader()
(它不存在)。打字错误将其更改为对grabsclosesHeader()
的函数调用会记录所有元素,直到
崩溃,因为它不再有父元素。任何地方都没有无限循环的迹象。
function grabClosestHeader (el) {
var parent = el.parentNode;
el = parent.firstChild;
while (el.tagName !== 'H2') {
el = el.nextSibling;
console.log(el);
if( el != null && el.tagName === 'H2') {
console.log('This is the H2 Tag');
}
if (el === null) {
console.log('This is NULL');
parent = parent.parentNode;
el = parent.firstChild;
}
}
// Then return the matched element
console.log(el.tagName);
return el;
}