firstElementChild在Internet Explorer 7中不起作用...我的选择是什么?

dol*_*phy 8 javascript

考虑下面的JavaScript:

var v;
if (this.children.length > 0) {
    v = this.firstElementChild.value;
}
Run Code Online (Sandbox Code Playgroud)

这适用于FireFox和Chrome的现代版本,但this.firstElementChild.value在Internet Explorer 7-8中引发异常.我还有另一种方法可以让它适用于所有浏览器吗?

更新 - 最终解决方案

我选择了以下内容:

v = (this.firstElementChild || this.children[0] || {}).value - 谢谢大家.

lon*_*day 8

this.firstElementChild应该在每个重要的浏览器栏IE <= 9和Firefox 3(QuirksMode)中工作.

this.children[0]将在每个重要的浏览器栏Firefox 3中工作,除了IE <= 9将注释节点计为元素节点(QuirksMode).这对您来说可能是也可能不是问题.

全能系统是这样的:

var node = this.firstChild,
    firstElementChild = null;

for ( ; node; node = node.nextSibling) {
    if (node.nodeType === 1) {
        firstElementChild = node;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

firstElementChild然后,如果存在,则将是第一个元素子元素null.this.firstElementChild出于性能原因,最好在执行循环之前查看是否存在.


小智 7

我不知道,也许this.children[0].value吧?

  • FF 3.0不支持`children`,所以你可能需要像`(this.firstElementChild || this.children [0]).value.此外,IE计算"children"中的注释节点. (2认同)