这个问题足以说明我在 HTML 这块的基础确实很差。
先说结论。这个问题的答案视 HTML 的版本而定:
- 如果是 HTML 4,这个问题的答案是“是”;
- 如果是 HTML 5,这个问题的答案是“否”。
事实上,H5 规范并没有规定 id 不能为数字。以下摘自 H5 规范:
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
虽然习惯上我们并不会让 id 为纯数字,但是让 id 为纯数字并不违反 HTML 5 的规范。
至于为什么有 id 不能为纯数字的说法,我个人认为主要是两点:
-
来自其他编程语言的习惯。我们一般不会用数字来命名变量,这是违反精神模型的;然而由于前端框架的普及,使用数字作为 id 和 key 的现象非常常见。
-
出于兼容性考虑。HTML 4 规范指出,id 必须以字母开头。但正如刚才说的,HTML 5 已经移除了这一限制。
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (": “), and periods (”.").