问题描述
为了更好地了解 textConent 和 nodeValue 之间的区别,我想知道为什么在我的代码中使用nodeValue不起作用。我有以下XML字符串,它通过jQuery回调通过AJAX加载。如果你看循环的中心,那么如果我使用nodeValue代替textContent,那么该部分将产生一个空值。
To better understand the difference between textConent and nodeValue I'd like to find out why using nodeValue in my code is not working. I have the following XML string which gets loaded through AJAX via a jQuery callback. If you look at the center of the loop, that section will produce a null value if I use nodeValue in place of textContent.
XML / p>
XML
<?xml version="1.0" encoding="UTF-8"?>
<Sensors>
<Sensor>
<id>56</id>
<state>false</state>
</Sensor>
</Sensors>
我使用下面的函数来解析XML。
I use this function below to parse the XML.
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;
}
推荐答案
节点的文本部分实际上是节点本身的一个小孩。如果一个节点没有数据,那么就会调用childNodes [0] .nodeValue将失败。在您尝试访问之前,您需要检查实际存在的子节点数。否则,您需要执行协议,要求在创建XML数据时不能包含空标签。
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. You need to check for how many childNodes are actually present before you attempt to access them. Otherwise you'll need to enforce a protocol that demands that when XML data is created it cannot contain empty tags.
这篇关于textContent工作但nodeValue不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!