gpt4 book ai didi

javascript - 为什么我们不直接使用元素 ID 作为 JavaScript 中的标识符?

转载 作者:IT王子 更新时间:2023-10-29 03:00:22 24 4
gpt4 key购买 nike

我使用过的所有浏览器都允许使用 id="myDiv" 访问元素,只需编写:

myDiv

参见此处:http://jsfiddle.net/L91q54Lt/

无论如何,这种方法的文档似乎很少,事实上,我遇到的来源甚至没有提及它,而是假设有人会使用

document.getElementById("myDiv")

或者也许

document.querySelector("#myDiv")

访问 DOM 元素,即使其 ID 事先已知(即未在运行时计算)。我可以说,如果有人无意中试图在更广泛的范围内重新定义 myDiv(虽然这不是一个好主意......),但后一种方法的优点是可以保证代码安全,并用一些不同的方法覆盖它值并在没有注意到冲突的情况下继续。

但除此之外呢?除了代码设计之外,使用上面的简短形式是否有任何问题,或者我在这里还缺少什么?

最佳答案

Anyway, this method seems to be quite poorly documented, and In fact, the sources I come across don't even give it a mention [...]

抛开对隐式声明的全局变量的依赖,缺乏文档是不使用它的一个重要原因。

明显将 id 值提升为全局变量不符合标准( HTML5 spec for the ID attribute 没有提及),因此,您不应该假设 future 的浏览器会实现它。

编辑:事实证明这种行为 符合标准的——在 HTML5 中, window 应该支持对“命名元素”的属性访问:

Named objects with the name name, for the purposes of the above algorithm, are those that are either:

  • child browsing contexts of the active document whose name is name,
  • a, applet, area, embed, form, frameset, img, or object elements that have a name content attribute whose value is name, or
  • HTML elements that have an id content attribute whose value is name.

来源:HTML 5 spec, 'Named access on window object" , 强调我的

基于此,标准合规性并不是避免这种模式的理由。但是,规范本身建议不要使用它:

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

关于javascript - 为什么我们不直接使用元素 ID 作为 JavaScript 中的标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325221/

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