我正在像这样向不同的元素添加唯一的 ID 和类,
<div id="%'@#K!NG,<$wE3T?">Sweet</div>
于是我抬头,What are valid values for the id attribute in HTML?在那里我读到了广受好评的:
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 (".").
但后来我自己试验,似乎它比那更灵活。 Both of these work:
$(document.getElementById("%'@#K!NG,<$wE3T?")).text();
document.getElementById("%'@#K!NG,<$wE3T?").innerHTML;
如果我包含像 !@#$%^&*()<>}| 这样的字符,是否存在一些我看不到的陷阱?在 id 名称中?
最佳答案
它将在许多浏览器中工作,但不保证工作。为了获得最大的安全性,请遵守标准。
这与:Why can't variable names start with numbers? 有关.
在 HTML/JS 中,现在这可能不是什么问题,但请记住你可以这样做:
>>> window.footer
<div id="footer" class="categories">
这几乎就是早期 JS 的工作方式。出于兼容性原因,它仍然有效。它实际上已经在 HTML5 中正式化,恕我直言,它是 HTML5 中较差的概念之一。我相当确定,每次您在实时应用程序中使用它时,Douglas Crockford 都会杀死一只可爱的小哺乳动物。 请参阅:DOM: element IDs are global variables .
关于javascript - `!@#$%^&*(` 等非字母数字字符是否可以用作有效 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21959063/