简体   繁体   English

textContent工作但nodeValue没有

[英]textContent working but nodeValue does not

To better understand the difference between textConent and nodeValue I'd like to find out why using nodeValue in my code is not working. 为了更好地理解textConentnodeValue之间的区别 ,我想找出为什么在我的代码中使用nodeValue不起作用。 I have the following XML string which gets loaded through AJAX via a jQuery callback. 我有以下XML字符串,它通过jQuery回调通过AJAX加载。 If you look at the center of the loop, that section will produce a null value if I use nodeValue in place of textContent. 如果你查看循环的中心,如果我使用nodeValue代替textContent,该部分将产生一个空值。

XML XML

<?xml version="1.0" encoding="UTF-8"?>
    <Sensors>
        <Sensor>
            <id>56</id>
            <state>false</state>
        </Sensor>
    </Sensors>

I use this function below to parse the XML. 我使用下面的函数来解析XML。

JavaScript JavaScript的

  function parseSensors(data,status,xhr) {
         var xml = xhr.responseXML;
         var sensors = xml.documentElement.childNodes;

         var list="<ul>";             
         for(var i=0; i < sensors.length; i++) {
             list= list +"<li>"+sensors[i].childNodes[0].textContent+"</li>";                 
         }
         list=list+"</u>";
         document.getElementById("real-time_active_sensors").innerHTML=list;            
     }

The text portion of a node is actually a child of the node itself. 节点的文本部分实际上是节点本身的子节点。 If a node has no data in it, such as then a call to childNodes[0].nodeValue will fail. 如果节点中没有数据,那么对childNodes [0] .nodeValue的调用将失败。 You need to check for how many childNodes are actually present before you attempt to access them. 在尝试访问之前,您需要检查实际存在多少个childNodes。 Otherwise you'll need to enforce a protocol that demands that when XML data is created it cannot contain empty tags. 否则,您需要强制执行一项协议,该协议要求在创建XML数据时不能包含空标记。

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

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