gpt4 book ai didi

具有多个元素的 Javascript document.getElementById()

转载 作者:行者123 更新时间:2023-11-28 13:36:44 42 4
gpt4 key购买 nike

当存在多个具有相同ID的元素时,document.getElementById()如何处理? MDN只是说:

Returns a reference to the element by its ID.

在文档的“注释”部分,我希望提及应该发生的事情,所有内容如下:

If there is no element with the given id, this function returns null.

所以我决定亲自找出答案,并在 Chrome 的开发控制台中进行了测试。这是我得到的:

> document.write('<div id="myid"></div>')
> document.getElementById("myid")
<div id="myid"></div>
> document.write('<span id="myid"></span>')
> document.getElementById("myid")
<div id="myid"></div>

它似乎只返回第一个值 - 有人可以澄清这一点吗?

最佳答案

由于代码运行的方式,它将返回文档中具有 ID 的第一个元素。从逻辑上讲,两个元素具有相同的 id 是非法的。那么为什么要寻找与已找到的元素具有相同 id 的另一个元素呢,应该只有一个元素具有该 ID。 大多数浏览器从上到下扫描文档,因此返回具有匹配 ID 的第一个元素。

关于具有多个元素的 Javascript document.getElementById(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874698/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com