Javascript:子节点的时候存在缺陷.长度显示太多的元素

Javascript: childNodes.length showing too many elements?

本文关键字:缺陷 显示 太多 元素 子节点 候存在 Javascript 存在      更新时间:2023-09-26

我得到一些奇怪的结果,而在JavaScript中解析一些XML。我在外部文件中有以下XML:

<?xml version="1.0" encoding="UTF-8" ?>
<alerts>
 <alert><![CDATA[ This is the first alert message in a series... ]]></alert>
 <alert><![CDATA[ This is the second alert message in a series, which features a <a href="http://www.facebook.com" target="blank">hyperlink</a>... ]]></alert>
 <alert><![CDATA[ This is the third alert message in a series, which features <span class="emphasizedAlertText">text formatted via a css rule</span> ]]></alert>
 <alert><![CDATA[ This is the fourth alert message in a series, which features a <span class="fauxHyperlink" onclick="someFunction();">javascript call</span>... ]]></alert>
</alerts>

通过XMLHttpRequest抓取文件后,我使用以下函数将其输出到页面:

function testFunc()
{
   var xhrRsp = 'failed to initialize';
   rslt = document.getElementById('rslt');
   if(xhr.readyState == 4)
      {
         if(xhr.status == 200)
         {
            xhrRsp = xhr.responseXML;
            xhrTree = xhrRsp.documentElement.childNodes;
            rslt.innerHTML = xhrRsp + ' (' + xhrTree.length + ' nodes) ';
            for(var i = 0; i < xhrTree.length; i++)
            {
               if(xhrTree[i].nodeName != '#text')
               {
                  rslt.innerHTML = rslt.innerHTML + '<br/>' + xhrTree[i].nodeName + ' (' + xhrTree[i].nodeType + ') ' + ' = ' + xhrTree[i].childNodes[0].nodeValue;
               }
            }
            //rslt.innerHTML = outMsg;
         }
   }
   else
   {
      xhrRsp = 'Loading...';
   }
}

当我在浏览器中运行脚本时,我得到如下结果:

Click Me
[object Document] (9 nodes) 
alert (1) = This is the first alert message in a series...
alert (1) = This is the second alert message in a series, which features a hyperlink...
alert (1) = This is the third alert message in a series, which features text formatted via a css rule
alert (1) = This is the fourth alert message in a series, which features a javascript call...

我很困惑为什么节点的数量返回为9,以及为什么这些节点中的其他节点都以#text的形式出现,我目前在上面的脚本中过滤掉了#text。我一直在四处寻找,不知道我错过了什么。

提前感谢!

这是W3C兼容浏览器的正确行为。元素之间的空白作为TextNode包含在DOM中。

您可能会发现,在IE8及以下版本中,没有生成文本节点。这是因为这些浏览器在这方面没有遵守规范。

我敢打赌你是在一个蹩脚的浏览器上运行的,它不处理空格。

无论如何,您正在使用if过滤某个节点,因此这并不奇怪。一些快速的日志记录可以非常快速地解决您的问题…