所以我有以下 HTML:
<div id="mainSectionNav" class="section-container auto" data-section="" style="">
<section class="active" style="padding-top: 50px;">
<p class="title" data-section-title="" style="left: 0px;">
<a href="#panel2">Dashboard</a>
</p>
</section>
<section>
<p class="title" data-section-title="" style="left: 97px;">
</section>
我正在尝试编写一个函数来返回链接文本“Dashboard”。
function zurbGetActiveSectionTab(elementId) {
var activeSectionLinkText = '';
var sectionLayout = document.getElementById(elementId);
var sections = sectionLayout.childNodes;
for(var i=0; i < sections.length; i++) {
var section = sections[i];
console.log("section tagName " + section.tagName);
if ($(section).hasClass('active')) {
var activeSectionParagraph = section.firstChild;
// if(sections[i].type == 'level2-div')
console.log("activeSectionParagraph tagName " + activeSectionParagraph.tagName);
var activeSectionLink = activeSectionParagraph.firstChild;
console.log("activeSectionLink tagName " + activeSectionLink.tagName);
activeSectionLinkText = activeSectionLink.innerHTML;
}
}
return activeSectionLinkText;
}
但是输出的是:
section tagName undefined
section tagName SECTION
activeSectionParagraph tagName undefined
TypeError: activeSectionLink is null
[Break On This Error]
这让我很困惑。
- 为什么sections[0]未定义?
- 为什么 activeSectinParagraph tagName 未定义
- 为什么 activeSectionLink 为空?
- activeSectionLink.innerHTML 是获取链接文本的正确方法吗?
抱歉问了这么多问题。我越把这个搞乱,我就越困惑。
最佳答案
childNodes还返回不同类型的节点,而不仅仅是元素。
如果您查看子级的长度,您会发现它比您预期的要大。如果需要,您可以通过检查nodeType来过滤掉它们。
for(var i=0; i < sections.length; i++) {
var section = sections[i];
if (section.nodeType != 1) {
continue;
}
....
关于javascript - 对 javascript HTML DOM 遍历感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174732/