有人可以向我解释一下 HTML getElementById() 方法的内部实现吗? 它是遍历整个 DOM 树来找到指定的元素,还是它足够智能以首先寻找附近的元素?
谢谢
最佳答案
实现完全(呃)依赖于实现。一些浏览器可能使用 hashmap 或类似的东西,也可能不使用(因为虽然 id
是 required to be unique ,但有很多编写不当的页面提供了重复的 id< 的无效标记
s)。 Internet Explorer 6 和 7 甚至不将 getElementById
限制为 id
值,它们 conflate namespaces terribly ,尽管微软已经清楚地看到了曙光,并且 IE8 和 IE9 都改进了这一点。
对于实现开源的浏览器,当然可以查一查。 Here's a link to the WebKit source , 和 here's one to Mozilla's (该行号可能会有所不同,如果您没有正确着陆,只需搜索 GetElementById
和 GetElementByIdInternal
)。这两个都来自 this related answer here on StackOverflow . (事实上,看看这个问题,我认为这个问题可能是重复的,尽管正如 Matthew 在下面的评论中指出的那样,事情进展得足够快,可能需要更新......)
关于javascript - GetElementByID() 的实现是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4578110/