我可以有一个带有 id
的元素吗?以数字开头还是完全是数字?
例如。像这样:
<div id="12"></div>
最佳答案
Can I have a div with id as number?
是的你可以。
id
仅由数字组成的值 are perfectly valid in HTML ;除了一个空间什么都可以。尽管早期的 HTML 规范更加严格( ref 、 ref ),需要一小组字符并以字母开头,但浏览器从不关心,这也是 HTML5 规范开放的重要原因。如 你要使用那些
id
使用 CSS 选择器(例如,使用 CSS 设置样式,或使用 querySelector
、 querySelectorAll
或使用 CSS 选择器的 jQuery 等库来定位它们),请注意这可能会很痛苦,因为 you can't use an id
starting with a digit in a CSS id
selector literally ;你必须逃避它。 (例如, #12
是一个无效的 CSS 选择器;你必须把它写成 #\31\32
。)因此,如果你打算将它与 CSS 选择器一起使用,以字母开头会更简单。为清楚起见,以上列表中的链接:
下面是一个使用
div
的例子与 id
“12”和用它做事的三种方式:document.getElementById
document.querySelector
(在支持它的浏览器上)它适用于我曾经使用过的所有浏览器(请参阅代码下方的列表)。现场示例:
(function() {
"use strict";
document.getElementById("12").style.border = "2px solid black";
if (document.querySelector) {
document.querySelector("#\\31\\32").style.fontStyle = "italic";
display("The font style is set using JavaScript with <code>document.querySelector</code>:");
display("document.querySelector(\"#\\\\31\\\\32\").style.fontStyle = \"italic\";", "pre");
} else {
display("(This browser doesn't support <code>document.querySelector</code>, so we couldn't try that.)");
}
function display(msg, tag) {
var elm = document.createElement(tag || 'p');
elm.innerHTML = String(msg);
document.body.appendChild(elm);
}
})();
#\31\32 {
background: #0bf;
}
pre {
border: 1px solid #aaa;
background: #eee;
}
<div id="12">This div is: <code><div id="12">...</div></code>
</div>
<p>In the above:</p>
<p>The background is set using CSS:</p>
<pre>#\31\32 {
background: #0bf;
}</pre>
<p>(31 is the character code for 1 in hex; 32 is the character code for 2 in hex. You introduce those hex character sequences with the backslash, <a href="http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier">see the CSS spec</a>.)</p>
<p>The border is set from JavaScript using <code>document.getElementById</code>:</p>
<pre>document.getElementById("12").style.border = "2px solid black";</pre>
我从未在浏览器中看到上述失败。这是一个 子集我见过它在以下浏览器中工作:
但是再次:如 您将在元素中使用 CSS 选择器,最好以字母开头;选择器如
#\31\32
阅读起来非常棘手。
关于javascript - 我可以拥有一个 ID 以数字开头的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563698/