DOM data-x 属性兼容性——这安全吗?
我想知道对元素使用 data-varname 属性的浏览器兼容性是什么样的?
在我的整个网站中,我使用数据属性来指示行号、参考 ID 等,以进行 ajax 删除和删除。插入。
例如:
<ul>
<li data-row="1">First Row <a href="#" data-row="1" data-id="123">remove</a></li>
<li data-row="2">Second Row <a href="#" data-row="1" data-id="111">remove</a></li>
</ul>
$(document).ready(function(){
$("li a").click(function(){
var index = $(this).attr("data-row");
$("li [data-row='" + index + "']").remove();
// ajax deletion in database referencing data-id attribute
});
});
我知道我可以引用锚点的父级来删除它,而不是查看元素的数据行属性,但这只是一个显示它的基本用法的示例..这实际上不是我正在做的。
我想知道使用这个 data- 属性有多“安全”。它是否非常普遍兼容,或者仍然有很多浏览器无法正常运行?
I was wondering what the browser compatibility looks like for using data-varname attributes for elements?
Throughout my site I'm using data- attributes to indicate row numbers, reference IDs, etc for ajax deletion & insertion.
For example:
<ul>
<li data-row="1">First Row <a href="#" data-row="1" data-id="123">remove</a></li>
<li data-row="2">Second Row <a href="#" data-row="1" data-id="111">remove</a></li>
</ul>
$(document).ready(function(){
$("li a").click(function(){
var index = $(this).attr("data-row");
$("li [data-row='" + index + "']").remove();
// ajax deletion in database referencing data-id attribute
});
});
I know i can just reference the anchor's parent to remove it rather than looking at the element's data-row attribute, but this is just an example to show basic usage of it.. this isn't actually what I'm doing.
I want to know how "safe" it is to use this data- attribute. Is it pretty univerisally compatible or are there still a good number number of browsers that won't function correctly with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是完全安全的。浏览器始终接受无法识别的属性。 data-* 属性所发生的一切是 HTML5 定义了 (a) 这些名称永远不会用于任何其他官方目的,以及 (b) 一个 API,以便更方便地在 JavaScript 中访问这些值。
如果您使用新的 API,那么您将需要一个适用于旧版浏览器和那些尚未对该 API 提供本机支持的浏览器的 Polyfill,但您所做的并不使用该 API。
It's completely safe. Browsers have always accepted unrecognised attributes. All that happened with the data-* attributes was that HTML5 defined (a) that those names will never be used for any other official purpose and (b) an API to make accessing those values in JavaScript more convenient.
If you use the new API, then you will need a polyfill for older browsers and those that do not yet have native support for the API, but what you are doing doesn't use that API.