javascript--无法获取[对象文本] 的文本内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4742409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript--can't get textContent of [Object Text]?
提问by Shawn
I want the script to find where it says, "anyword" in the xml (within the tag of course), and stop on that. the below accomplishes that fine.
我希望脚本在 xml 中找到它所说的“任意词”(当然在标签内),然后停止。下面就完成了。
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'. so i tried something like this and it came back with the very last element in the collection, instead of the next one.
但是,我想更进一步,并能够在找到“anyword”后将“变量”设置为下一个节点。所以我尝试了这样的事情,它返回了集合中的最后一个元素,而不是下一个。
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].nextSiblingit comes back [Object Text]
这回来了。在这里扯我的头发。如果它有助于回答任何问题,如果我只是x[i].nextSibling说它会回来[Object Text]
any help?
有什么帮助吗?
采纳答案by Mike Samuel
By x[i].textContent = "anyword"do you mean x[i].textContent == "anyword"?
通过x[i].textContent = "anyword"你的意思x[i].textContent == "anyword"?
回答by Hemlock
This is a common problem for people. The modern browsers (basically all them except IE) will add text nodes between elements. Those text nodes only contain the whitespace and aren't of a lot of use. Use this function to find the next node.
这是人们普遍存在的问题。现代浏览器(基本上除了 IE 之外的所有浏览器)都会在元素之间添加文本节点。这些文本节点只包含空格,并没有多大用处。使用此函数查找下一个节点。
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
回答by Marc Bouvier
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++)

