.previousSibling是否始终返回父节点的Text节点? [英] Does .previousSibling always return the parent's Text node first?
问题描述
我使用本机DOM方法(我知道,对吗?),我有一个这样的结构:
I'm stuck using native DOM methods (I know, right?) and I have a structure like this:
<div>
<input>
<a>
</div>
我在< a>
标签,并希望从输入中检索值。在Chrome / OS X上,像
I'm using an onClick on the <a>
tag, and want to retrieve the value from the input. On Chrome/OS X, something like
this.previousSibling.previousSibling.value
可以正常运行。因为第一个 .previousSibling
返回< div>
的Textnode,而在此之前还有一个获取我想要的输入。
will work well. I double it though because the first .previousSibling
returns the <div>
's Textnode, and one more before that gets the input that I want.
我的问题是: .previousSibling
总是返回父文本节点存在?
My question is: does .previousSibling
always return the parent's text node if it exists?
谢谢!
我的黑客解决方案是(跨浏览器),以确保我得到如下所示的正确元素:
My hacky solution was (cross browser) to ensure I get the right element looked like this:
var el = this;
while(el.nodeType == 3 || el.tagName && el.tagName !== 'INPUT') {
el = el.previousSibling
};
console.log(el.value);
位置具体,但跨浏览器工作,足够轻便折腾成$ code > onClick 为我的需要。感谢您的帮助,以确定这里有什么问题(特别是HTML之间的换行符)
Location specific, but works cross browser, and is light enough to toss into an onClick
for my needs. Thanks for the help in figuring out what was at issue here (line breaks between HTML in particular)
推荐答案
如果
存在,.previousSibling是否会返回父文本节点?
Does .previousSibling always return the parent's text node if it exists?
否。它返回前一个兄弟姐妹。在你的情况下,在 a
元素之前有一个文本节点(新行),所以它返回。
No. It returns the immediately preceding sibling. In your case, there is a text node (a new line) immediately preceding the a
element, so it returns that.
如果您删除白色空间,则应按预期方式工作:
If you remove the white space it should work as expected:
<div>
<input><a></a> <!-- input is immediately preceding anchor -->
</div>
但是,这不是一个特别好的解决方案。请参阅@ Esailija的更好的答案!
However, that's not a particularly nice solution. See @Esailija's answer for a nicer one!
这篇关于.previousSibling是否始终返回父节点的Text节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!