Javascript 我可以有一个 id 为数字的 div 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5672903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:23:32  来源:igfitidea点击:

can I have a div with id as number?

javascripthtml

提问by jslearner

Can I have a divwith idas number?

我可以有一个divwith as 号码吗?id

eg <div id="12"></div>

例如 <div id="12"></div>

回答by T.J. Crowder

Can I have a div with id as number?

我可以有一个以 id 为数字的 div 吗?

Yes, you can.

是的你可以。

idvalues that consist solely of digits are perfectly valid in HTML; anything but a space is okay. And although earlier HTML specs were more restrictive (ref, ref), requiring a small set of chars and starting with a letter, browsers never cared, which is a big part of why the HTML5 specification opens things up.

id仅由数字组成的值在 HTML 中完全有效;除了空格什么都可以。尽管早期的 HTML 规范限制性更强(refref),需要一小组字符并以字母开头,但浏览器从不关心,这也是 HTML5 规范开放的重要原因。

Ifyou're going to use those ids with CSS selectors (e.g, style them with CSS, or locate them with querySelector, querySelectorAll, or a library like jQuery that uses CSS selectors), be aware that it can be a pain, because you can't use an idstarting with a digit in a CSS idselector literally; you have to escape it. (For instance, #12is an invalid CSS selector; you have to write it #\31\32.) For that reason, it's simpler to start it with a letter if you're going to use it with CSS selectors.

如果你要使用这些ids的CSS选择器(例如,风格他们CSS,或找到他们querySelectorquerySelectorAll或者像jQuery库,它使用CSS选择器),要知道,它可以是一个痛苦的,因为你可以”吨使用id与在CSS的一个数字的起始id选择字面上; 你必须逃避它。(例如,#12是一个无效的 CSS 选择器;您必须编写它#\31\32。)因此,如果您打算将它与 CSS 选择器一起使用,以字母开头会更简单。

Those links above in a list for clarity:

为清楚起见,以上列表中的链接:

Below is an example using a divwith the id"12" and doing things with it three ways:

下面是一个使用div带有id“12”并用它做事的三种方式的例子:

  1. With CSS
  2. With JavaScript via document.getElementById
  3. With JavaScript via document.querySelector(on browsers that support it)
  1. 使用 CSS
  2. 使用 JavaScript 通过 document.getElementById
  3. 使用 JavaScript 通过document.querySelector(在支持它的浏览器上)

It works on every browser I've ever thrown at it (see list below the code). Live Example:

它适用于我曾经使用过的所有浏览器(请参阅代码下方的列表)。现场示例:

(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);
  }
})();
# {
  background: #0bf;
}
pre {
  border: 1px solid #aaa;
  background: #eee;
}
<div id="12">This div is: <code>&lt;div id="12">...&lt;/div></code>
</div>
<p>In the above:</p>
<p>The background is set using CSS:</p>
<pre># {
    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>

I've never seen the above fail in a browser. Here's a subsetof the browsers I've seen it work in:

我从未在浏览器中看到上述失败。这是我看到它在其中工作的浏览器的一个子集

  • Chrome 26, 34, 39
  • IE6, IE8, IE9, IE10, IE11
  • Firefox 3.6, 20, 29
  • IE10 (Mobile)
  • Safari iOS 3.1.2, iOS 7
  • Android 2.3.6, 4.2
  • Opera 10.62, 12.15, 20
  • Konquerer 4.7.4
  • 铬 26、34、39
  • IE6、IE8、IE9、IE10、IE11
  • 火狐 3.6、20、29
  • IE10(移动)
  • Safari iOS 3.1.2、iOS 7
  • 安卓 2.3.6、4.2
  • 歌剧 10.62, 12.15, 20
  • 征服者 4.7.4

But again: Ifyou're going to use CSS selectors with the element, it's probably best to start it with a letter; selectors like #\31\32are pretty tricky to read.

但同样:如果您要对元素使用 CSS 选择器,最好以字母开头;选择器 like#\31\32很难阅读。

回答by Hristo

From the HTML 5 specs...

HTML 5 规范...

The id attribute specifies its element's unique identifier (ID). [DOM]

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

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.

An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

id 属性指定其元素的唯一标识符 (ID)。[DOM]

该值在元素的主子树中的所有 ID 中必须是唯一的,并且必须至少包含一个字符。该值不得包含任何空格字符。

对于 ID 可以采用的形式没有其他限制;特别是,ID 可以仅包含数字、以数字开头、以下划线开头、仅包含标点符号等。

元素的唯一标识符可用于多种用途,最显着的是作为使用片段标识符链接到文档特定部分的一种方式,作为在编写脚本时定位元素的一种方式,以及作为一种从CSS。

标识符是不透明的字符串。不应从 id 属性的值中推导出特定含义。

So... yes :)

所以......是的:)

From the HTML 4.01 specs...

HTML 4.01 规范...

ID 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 (".").

ID 必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_")、冒号 ( ":") 和句点 (".")。

So... no :(

所以不行 :(

回答by andddrey

You can also select that type of id(though it is definitely not the best practice to create such an id that starts with a number) by doing the following:

您还可以通过执行以下操作来选择该类型的 id(尽管创建以数字开头的 id 绝对不是最佳做法):

document.querySelector('div[id="12"]'); //or 
document.querySelectorAll('div[id="12"]'); //if you have multiple elements with equal ID.

回答by Zarathuztra

From a maintainability standpoint this is a bad idea. ID's should be at least somewhat descriptive of what they represent. Prefix it with something meaningful to be compliant with what others have already answered with. For example:

从可维护性的角度来看,这是一个坏主意。ID 至少应该对它们所代表的内容有所描述。给它加上一些有意义的前缀,以符合其他人已经回答的问题。例如:

<div id ="phoneNumber_12" > </div>

回答by Pancho

While TJ Crowder's answer is conceptually good, it doesn't work for descendant CSS selectors.

虽然 TJ Crowder 的答案在概念上很好,但它不适用于后代 CSS 选择器。

Escaping only the first character followed by space does work however (as at Chrome 49)

但是,仅转义第一个字符后跟空格确实有效(如 Chrome 49)

Assume the following HTML snippet:

假设有以下 HTML 片段:

<td id="123456">
 <div class="blah">
  <div class="yadah">play that funky music</div>
 </div>
</td>

The following statement:

以下声明:

document.querySelector("#\31 23456 .blah .yadah").style.fontStyle = "italic";

correctly displays play that funky music

正确显示播放时髦的音乐

回答by Anand Thangappan

As pointed out in other responses, the answer is technically:

正如其他回复中所指出的,从技术上讲,答案是:

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 (".").

However, as a practical matter, you will be somewhat more limited if you want your documents to work with a variety of browsers, CSS editors, and JavaScript frameworks.

但是,实际上,如果您希望您的文档与各种浏览器、CSS 编辑器和 JavaScript 框架一起使用,您将受到更多限制。

As noted in other responses, jQuery has problems with ids that contain periods and colons.

正如其他回复中所述,jQuery 存在包含句点和冒号的 id 问题。

A more subtle problem is that some browsers have been known to mistakenly treat id attribute values as case-sensitive. That means that if you type id="firstName" in your HTML (lower-case 'f') and .FirstName { color: red } in your CSS (upper-case 'F'), a buggy browsers will not set the element's color to red. Because both definitions use valid characters for the id, you will receive no error from a validation tool.

一个更微妙的问题是已知某些浏览器错误地将 id 属性值视为区分大小写。这意味着,如果您在 HTML(小写 'f')中输入 id="firstName" 并在 CSS 中输入 .FirstName { color: red }(大写 'F'),则有问题的浏览器将不会设置元素的颜色为红色。因为这两个定义都使用有效字符作为 ID,所以您不会收到来自验证工具的错误。

You can avoid these problems by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name.

您可以通过严格遵守命名约定来避免这些问题。例如,如果您完全限制自己使用小写字符,并且总是用连字符或下划线分隔单词(但不能同时使用两者,选择一个,不要使用另一个),那么您就有了一个易于记忆的模式。你永远不会想知道“是名字还是名字?” 因为您将始终知道应该键入 first_name。

Same Question is Already ask

同样的问题已经问了

What are valid values for the id attribute in HTML?

HTML 中 id 属性的有效值是什么?

回答by Rafe Kettler

No. It has to start with a letter. See http://www.electrictoolbox.com/valid-characters-html-id-attribute/. You can use numbers after the first character, however, e.g. a1or theansweris42.

不,它必须以字母开头。请参阅http://www.electrictoolbox.com/valid-characters-html-id-attribute/。但是,您可以在第一个字符后使用数字,例如a1theansweris42