javascript - 为什么元素id不能以整数开头?

标签 javascript jquery

<分区>

我正在学习 jQuery 选择器。

w3schools tutorial说“不要以数字开头 id 属性。这可能会导致某些浏览器出现问题”。我测试了一下,确实不行。请问这个问题的技术原因是什么?

最佳答案

Why can an element id not start with an integer?

他们可以。但是 CSS ID 选择器不能以数字开头。例如,这个 HTML is valid :

<div id="1foo">testing 1 2 3</div>

...但此 CSS 无效:

#1foo {
    color: green;
}

CSS standard表示 id 选择器不能以未转义的数字开头:

An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an CSS identifiers.

然后 defining CSS identifier :

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

(我的重点。)

因此理论上,您可以通过转义 CSS 选择器中的数字来解决 #1foo 不起作用的问题。例如:

HTML:

<div id="1foo">testing 1 2 3</div>

CSS:

#\31 foo {
    color: green;
}

...其中 31“1” 的十六进制字符代码。实例:

#\31 foo {
  color: green;
}
<div id="1foo">testing 1 2 3</div>

但是选择器不能从字面上以数字开头,一般来说,这是一个我会避免打扰的麻烦。我也不能说在执行此操作时需要解释 CSS 选择器的各种东西工作得如何。 jQuery 正确处理它,FWIW。例如:

$("#\\31 foo").css("color", "blue");

...有效。实例:

setTimeout(function() {
  $("#\\31 foo").css("color", "blue");
}, 2000);
#\31 foo {
  color: green;
}
<div id="1foo">testing 1 2 3, this should be green, and in two seconds it'll turn blue</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

(请注意,您必须转义字符串中的反斜杠,因为反斜杠在 JavaScript 字符串中很特殊,因此要在选择器中获得实际的反斜杠,您需要在字符串中使用两个反斜杠。)

至于 为什么 CSS 会有这个限制(以及为什么 HTML used to,尽管浏览器从未强制执行),我们只能推测。 Alien 先生在评论中指出,大多数编程语言不允许以数字作为起始标识符。 HTML 和 CSS 当然不是编程语言,但是通过 HTML 创建的 id 值反射(reflect)为 DOM 对象中的属性名称,可以通过编程语言访问。可能只是制定规范的人遵循了他们认为的惯例,或者试图提供与编程语言的某种兼容性。不过,这只是猜测。

关于javascript - 为什么元素id不能以整数开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22141358/

相关文章:

java - 提交操作时

jquery - 增量 CSS 定位不起作用

javascript - 如何在链接单击时将图像加载到 Canvas 中

javascript - VBA onclick 事件 Internet Explorer 不工作

javascript - Firefox Webextension - TypeError : browser. contextMenus 未定义

javascript - 从表格单元格中获取值并转换为数组

javascript - 将数组拆分为 block 并对每个索引求和,然后合并到另一个数组中

javascript - 如何使用 jquery 获取所有 css 的设置?

javascript - 值未在表 Angular 中呈现

javascript - 如何在 flutter 中将一个图标更改为两个不同的图标?