如何使用 HTML 数据集属性删除 data-* 属性
根据数据集规范,如何element.dataset 是否意味着删除数据属性?考虑一下:
<p id="example" data-a="string a" data-b="string b"></p>
如果你这样做:
var elem = document.querySelector('#example');
elem.dataset.a = null;
elem.dataset.b = undefined;
elem.dataset.c = false;
elem.dataset.d = 3;
elem.dataset.e = [1, 2, 3];
elem.dataset.f = {prop: 'value'};
elem.dataset.g = JSON.stringify({prop: 'value'});
DOM 在 Chrome 和 Firefox 中变成这样:
<p id="example"
data-a="null"
data-b="undefined"
data-c="false"
data-d="3"
data-e="1,2,3"
data.f="[object Object]"
data.g="{"prop":"value"}"
></p>
Chrome/Firefox 实现模仿 设置属性。它基本上首先应用.toString()
。除了对 null
的处理之外,这对我来说很有意义,因为我希望 null
会删除该属性。否则,数据集 API 如何执行等效操作:
elem.removeAttribute('data-a');
布尔属性又如何:
等效于
嗯。
According to the dataset specification, how is element.dataset meant to delete data attributes? Consider:
<p id="example" data-a="string a" data-b="string b"></p>
If you do this:
var elem = document.querySelector('#example');
elem.dataset.a = null;
elem.dataset.b = undefined;
elem.dataset.c = false;
elem.dataset.d = 3;
elem.dataset.e = [1, 2, 3];
elem.dataset.f = {prop: 'value'};
elem.dataset.g = JSON.stringify({prop: 'value'});
the DOM becomes this in Chrome and Firefox:
<p id="example"
data-a="null"
data-b="undefined"
data-c="false"
data-d="3"
data-e="1,2,3"
data.f="[object Object]"
data.g="{"prop":"value"}"
></p>
The Chrome/Firefox implementations mimic setAttribute. It basically applies .toString()
first. This makes sense to me except for the treatment of null
because I would expect that null
would remove the attribute. Otherwise how does the dataset API do the equivalent of:
elem.removeAttribute('data-a');
And what about boolean attributes:
<p data-something>
is equivalent to <p data-something="">
Hmm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“删除”不会删除数据集元素吗?例如:
Wouldn't 'delete' remove dataset element? E.g.:
一个相当简单直接的方法:
A rather simpler and straightforward approach:
根据 MDN 您需要使用删除运算符删除数据集元素
As per MDN you need to use the delete operator to remove a dataset element
这是为了删除所有 data-* 属性。您可以在 for 循环中添加条件以仅删除特定的数据属性。希望这有帮助:)
This is to remove all the data-* attributes. You can add a condition in the for loop to remove only particular data-attribute. Hope this helps :)