[英]javascript--can't get textContent of [Object Text]?
I want the script to find where it says, "anyword" in the xml (within the tag of course), and stop on that.我希望脚本在 xml 中找到它所说的“任意词”(当然在标签内),然后停止。 the below accomplishes that fine.下面就完成了。
var xmlDoc = loadXMLDoc("nhl.xml");
var x = xmlDoc.getElementsByTagName("tagname");
for (var i=0;i<=x.length;i++){
if (x[i].textContent = "anyword") {
var variable = x[i].textContent;
}
}
However I want to take it one step further and be able to set 'variable' to the next node after it finds 'anyword'.但是,我想更进一步,并能够在找到“anyword”后将“变量”设置为下一个节点。 so i tried something like this and it came back with the very last element in the collection, instead of the next one.所以我尝试了这样的事情,它返回了集合中的最后一个元素,而不是下一个。
var xmlDoc = loadXMLDoc("nhl.xml");
var x = xmlDoc.getElementsByTagName("tagname");
for (var i=0;i<=x.length;i++){
if (x[i].textContent = "anyword") {
var variable = x[i+1].textContent;
}
}
so i edited the last line again and made it所以我再次编辑了最后一行并制作了它
var variable = x[i].nextSibling.textContent;
this came back null.这回来了。 ripping my hair out here.在这里扯我的头发。 if it helps to answer any, if i just put it x[i].nextSibling
it comes back [Object Text]
如果它有助于回答任何问题,如果我只是把它放在x[i].nextSibling
它回来[Object Text]
any help?有什么帮助吗?
x[i].textContent = "anyword"
是指x[i].textContent == "anyword"
吗?
This is a common problem for people.这是人们普遍存在的问题。 The modern browsers (basically all them except IE) will add text nodes between elements.现代浏览器(基本上除了 IE 之外的所有浏览器)都会在元素之间添加文本节点。 Those text nodes only contain the whitespace and aren't of a lot of use.这些文本节点只包含空格,并没有多大用处。 Use this function to find the next node.使用此函数查找下一个节点。
function nextSibling(node) {
do {
node = node.nextSibling;
} while (node && node.nodeType != 1) ;
return node
}
It gets explained pretty well here: JavaScript XML Parsing它在这里得到了很好的解释: JavaScript XML Parsing
var xmlDoc = loadXMLDoc("nhl.xml");
var x = xmlDoc.getElementsByTagName("tagname");
for (var i=0;i<=x.length;i++){
if (x[i].textContent = "anyword") {
var variable = x[i+1].textContent;
}
}
I did't look in details but this seems odd to me :我没有仔细看,但这对我来说似乎很奇怪:
for (var i=0;i<=x.length;i++)
Have you tried你有没有尝试过
for (var i=0;i<x.length;i++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.