如何使用HTML5数据集删除data- *属性 [英] How to remove data-* attributes using HTML5 dataset

查看:389
本文介绍了如何使用HTML5数据集删除data- *属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据数据集规范 element.dataset 是如何删除数据属性的?考虑:

According to the dataset spec, how is element.dataset meant to delete data attributes? Consider:

<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中变为:

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>

Chrome/Firefox实现模仿 setAttribute .它基本上首先应用.toString().这对我来说是有意义的,除了对null的处理,因为我希望null会删除该属性.否则,数据集API的作用等同于:

The Chrome/Firefox implementation mimics 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');

关于布尔属性呢?

<p data-something>等同于<p data-something="">毫米.

推荐答案

是否删除"删除数据集元素?例如:

Wouldn't 'delete' remove dataset element? E.g.:

<div id="a1" data-foo="bar">test</div>

<script>
var v = document.getElementById('a1');  
alert(v.dataset.foo);
delete v.dataset.foo;
alert(v.dataset.foo);
</script>

这篇关于如何使用HTML5数据集删除data- *属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆