考虑下面的JavaScript:
var v;
if (this.children.length > 0) {
v = this.firstElementChild.value;
}
这在FireFox和Chrome的现代版本中有效,但是this.firstElementChild.value
在Internet 7-8中抛出了一个异常。对于我来说,还有别的方法可以让它在所有浏览器上运行吗?
更新--最终解决方案
我做了以下几点:
v = (this.firstElementChild || this.children[0] || {}).value
--感谢所有的人。
发布于 2011-06-13 16:30:00
我不知道,也许是this.children[0].value
发布于 2011-06-13 16:39:35
this.firstElementChild
应该在每个重要的浏览器栏IE、<=9和Firefox3 (QuirksMode)中工作。
this.children[0]
将在每个重要的浏览器栏火狐3中工作,除了IE <=9将注释节点作为元素节点(QuirksMode)。这对你来说可能是问题,也可能不是。
这个系统是这样的:
var node = this.firstChild,
firstElementChild = null;
for ( ; node; node = node.nextSibling) {
if (node.nodeType === 1) {
firstElementChild = node;
break;
}
}
如果存在第一个元素,firstElementChild
将是第一个子元素,否则为null
。出于性能原因,最好在执行循环之前查看this.firstElementChild
是否存在。
发布于 2011-06-13 16:33:53
如果您的代码位于事件处理程序中,并且函数被绑定为"attachEvent“,则"this”关键字绑定到"window“对象,而不是HTMLElement。尝试:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
检查properties.html。
https://stackoverflow.com/questions/6333249
复制相似问题