gpt4 book ai didi

javascript - 使用带有数字 ID 的 querySelector

转载 作者:IT王子 更新时间:2023-10-29 02:49:09 27 4
gpt4 key购买 nike

据我了解,HTML5 规范允许您使用像这样的数字 ID。

<div id="1"></div>
<div id="2"></div>

我可以使用 getElementById 访问这些内容,但不能使用 querySelector。如果我尝试执行以下操作,我会在控制台中收到 SyntaxError: DOM Exception 12

document.querySelector("#1")

我很好奇为什么使用数字作为 ID 不起作用 querySelector 而 HTML5 规范说这些是有效的。我尝试了多种浏览器。

最佳答案

它是有效的,但需要一些特殊处理。来自这里:http://mathiasbynens.be/notes/css-escapes

Leading digits

If the first character of an identifier is numeric, you’ll need to escape it based on its Unicode code point. For example, the code point for the character 1 is U+0031, so you would escape it as \000031 or \31 .

Basically, to escape any numeric character, just prefix it with \3 and append a space character ( ). Yay Unicode!

所以你的代码最终会是(先是 CSS,然后是 JS):

#\31  {
background: hotpink;
}

document.getElementById('1');
document.querySelector('#\\31 ');

关于javascript - 使用带有数字 ID 的 querySelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306204/

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