T.J*_*der 52
我可以将id作为数字的div吗?
是的你可以.
id仅由数字组成的值在HTML中完全有效 ; 除了空间之外什么也没关系.虽然早期的HTML规范更具限制性(ref,ref),需要一小组字符并以字母开头,浏览器从不关心,这是HTML5规范开放的重要原因.
如果你要使用这些ids的CSS选择器(例如,风格他们CSS,或找到他们querySelector,querySelectorAll或者像jQuery使用CSS选择器库),要知道,它可以是一个痛苦的,因为你可以" t id在字面意义上使用CSS id选择器中的数字开头 ; 你必须逃脱它.(例如,#12是一个无效的CSS选择器;你必须编写它#\31\32.)因此,如果你要将它与CSS选择器一起使用,那么用字母启动它会更简单.
为清晰起见,列表中的上述链接:
下面是使用div带有id"12" 的示例并使用三种方式处理它:
document.getElementByIddocument.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);
}
})();Run Code Online (Sandbox Code Playgroud)
#\31\32 {
background: #0bf;
}
pre {
border: 1px solid #aaa;
background: #eee;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我从来没有在浏览器中看到上述失败.这是我见过的浏览器的一个子集:
但是又一次:如果你要使用带有元素的CSS选择器,最好用一个字母开始它; 像选择器一样#\31\32非常难以阅读.
来自HTML 5规范 ......
id属性指定其元素的唯一标识符(ID).[DOM]
该值必须在元素的主子树中的所有ID中唯一,并且必须至少包含一个字符.该值不得包含任何空格字符.
ID可以采取什么形式没有其他限制; 特别是,ID可以只包含数字,以数字开头,以下划线开头,只包括标点符号等.
元素的唯一标识符可用于各种目的,最明显的是作为使用片段标识符链接到文档的特定部分的方式,作为在编写脚本时定位元素的方式,以及作为对特定元素进行样式设置的方式CSS.
标识符是不透明的字符串.不应从id属性的值派生特定含义.
所以...是的:)
来自HTML 4.01规范 ......
ID必须以字母([A-Za-z])开头,后面可以跟任意数量的字母,数字([0-9]),连字符(" - "),下划线("_"),冒号( ":")和句号(".").
所以不行 :(
Raf*_*ler -3
不可以,必须以字母开头。请参阅http://www.electrictoolbox.com/valid-characters-html-id-attribute/。不过,您可以在第一个字符后使用数字,例如a1或theansweris42。
| 归档时间: |
|
| 查看次数: |
34343 次 |
| 最近记录: |