为脚本标签指定 ID
我遇到过一个场景,为 script
元素提供 id
属性可以轻松解决问题。但是,在阅读 w3schools< 中的 script
元素之后/a> 和 quirksmode ,似乎这样做可能会产生一些不可预见的情况结果。
有人在使用 Chrome、Safari、FF3 以上和 IE 7 以上等浏览器时遇到过这些问题吗?
I came across a scenario where giving a script
element an id
attribute would solve a problem easily. However, after reading about the script
element at w3schools and quirksmode, it seems doing so could have some unforeseen consequences.
Has anyone come across any of these issues with browsers such as Chrome, Safari, FF3 up and IE 7 up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
请记住,在任何元素上设置
id
都会引入一个与id
属性同名的新全局变量:Keep in mind that setting the
id
on any element introduces a new global variable with the same name as theid
attribute:如果您仍然必须支持 Netscape 4,那么您就会遇到很多麻烦 – 以及其他开发人员世界的遗憾和哀悼。
简短的回答,我不会担心。
If you're still having to support Netscape 4, you've got a lot of trouble – and the pity and condolences of the rest of the developer world.
Short answer, I wouldn't worry about it.
我知道已经过去很长一段时间了,但我认为当您查看 W3 时最好指出这一点学校对 script 标签的定义,你有时会看到
在这些属性中,ta-da,你会找到你可爱的 id。
对于很多标签来说也是如此,这肯定会给我们带来很大的灵活性,让我们从帽子里变出那些漂亮的技巧。
I know a long time has passed, but I thought it would be nice to point that when you look at W3 Schools definition of the script tag, you see at some point that
and amongst those attributes, ta-da, you will find your lovely id.
The same goes for a whole lot of tags, which will certainly give us a lot of flexibility when pulling those nice trick from the hat.
我认为浏览器向
script
元素添加id
属性不会出现问题。在我的一些通过 JavaScript 加载其他 JavaScript 的网站上,我添加了一个
class
属性,以便更轻松地引用它们。验证者没有抱怨。I don't think a browser would have a problem by adding an
id
attribute to ascript
element.On some of my sites, that load additional JavaScripts via JavaScript, I have added a
class
attribute to make referencing them easier. The validator did not complain.在当前所有浏览器中都很好。
唯一出现
错误的浏览器是 Netscape 4,我们很久以前就不再关心它了。
该 quirksmode 页面似乎已经严重过时了,因为它使用了
language
属性、脚本如果我们谈论
属性兼容性问题:
defer
并非在所有地方都有效,因此不要依赖它;charset
并非在任何地方都有效,并且所服务脚本的 Content-Type 上的 charset 参数也不起作用,因此您的脚本字符集最好与页面匹配;type
应始终为text/javascript
,而不是编写 RFC 4329 的学究希望您使用的非工作替代方案之一。It's fine in all current browsers.
The only browser that got
<script id>
wrong was Netscape 4, which we stopped caring about a long, long time ago.That quirksmode page seems to be badly out of date, what with its use of
language
attributes, script<!--
hiding, andapplication/x-javascript
. Its advice about avoiding<script>
in the<body>
(and putting it in<head>
instead) is at odds with today's encouraged practices.If we're talking
<script>
attribute compatibility problems:defer
doesn't work everywhere so don't rely on it;charset
doesn't work everywhere, and neither does the charset parameter on the served script's Content-Type, so your script charset had better match the page;type
should always betext/javascript
and not one of the non-working alternatives the pedants who wrote RFC 4329 would like you to use.