【问题标题】:HTML IDs that start with a number以数字开头的 HTML ID
【发布时间】:2017-04-23 16:16:13
【问题描述】:

我在我的 HTML 中为 id 生成 GUID,例如

<div id="9121c01e-888c-4250-922f-cf20bcc7d63f">...</div>

根据 HTML5 规范,这是有效的。但是,如果您尝试使用 document.querySelector 或 document.querySelectorAll 查找此类元素,您将收到一条错误消息,指出选择器无效。

我知道对于 CSS 规则,这样的 ID 无效。 'document' 的 querySelector 方法是否依赖 CSS?

【问题讨论】:

  • 不知何故我的示例行消失了:
  • 发生这种情况是因为它不是一个有效的 CSS 选择器。您可以添加前缀、使用 getElementById 或将选择器更改为 [id="9121c01e-888c-4250-922f-cf20bcc7d63f"]
  • 我知道这不是答案,但是将它们写入 data-guid="" 而不是将它们放入 ID 类不是更好吗?
  • 如果您使用id 进行搜索,为什么不直接使用.getElementById?它更快更简单。

标签: javascript html


【解决方案1】:

'document' 的 querySelector 方法是否依赖 CSS?

您传递的字符串 querySelectorquerySelectorAll 是 CSS 选择器。所以是的,它们遵循 CSS 选择器的规则,其中之一(正如您提到的)是 ID 选择器不能以未转义的数字开头。所以它们本身并不依赖 CSS,而是遵循 CSS 选择器的语法。

您可以通过转义第一个数字(相当丑陋*)来选择该元素:

var e = document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f");

...或使用属性选择器:

var e = document.querySelector("[id='121c01e-888c-4250-922f-cf20bcc7d63f']");

例子:

document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f").innerHTML = "Yes!";
document.querySelector("[id='9121c01e-888c-4250-922f-cf20bcc7d63f']").style.color = "green";
&lt;div id="9121c01e-888c-4250-922f-cf20bcc7d63f"&gt;...&lt;/div&gt;

当然,如果您只是通过其 ID 获取元素而不使用以 ID 开头的复合选择器,则只需使用 getElementById,它不使用 CSS 选择器,只是作为纯文本的 ID 值:

var e = document.getElementById("9121c01e-888c-4250-922f-cf20bcc7d63f");

仅当您使用复合选择器 ("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f &gt; span a") 或将选择器字符串传递到您无法控制且您知道将使用 querySelector 的东西时才需要其他形式。


* 在 CSS 选择器中,\ 后跟最多六个十六进制字符(如果不使用所有六个字符,则加上一个空格)指定十六进制字符代码。 0x39 是数字 9 的字符代码。当然,我们必须对字符串文字中的\ 进行转义,否则它会被字符串文字消耗掉。

【讨论】:

  • document.getElementById();与第一个字符为数字一起使用,似乎是一个更好的选择?
  • @Riku:我的意思是说,是的,如果你没有将它与其他东西结合起来(例如,[id="...."] &gt; span a)。
【解决方案2】:

是的,他们使用 CSS 选择器

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Syntax
element = document.querySelector(selectors);
where

element is an Element object.
selectors is a string containing one or more CSS selectors separated by commas.

但是当您将 GUID 附加为 id 时,您可以使用 document.getElementById();

它支持这种情况。

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 2011-01-18
    • 2021-08-21
    • 2015-09-05
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多