这很有趣。但我通过编写如下示例代码研究了一些有趣的事实。
function hello(){
var el = document.querySelector('#user');
el.dataset.dateOfBirth = '1960-10-03';
}
function undIt(){
var el = document.querySelector('#user');
el.dataset.dateOfBirth = undefined;
}
hello()
alert(document.querySelector('#user').dataset.dateOfBirth)
undIt()
alert(document.querySelector('#user').dataset.dateOfBirth)
delete document.querySelector('#user').dataset.dateOfBirth;
的js提琴手链接http://jsfiddle.net/nirus/f92chmdp/1/
当我评论的删除声明我发现,该数据集变量在DOM树仍然存在(设置为未定义字符串)看到下面的图片
当我取消评论删除声明我可以看到它已从DOM树中删除。查看该图像下面
结论:作者已经用delete关键字完全去除数据变量和它的持久性的参考。
---------------------------- *****根据用户的评论guest271314 ***** * ------------------
我做了一些研究,是的,是的,jQuery实现是不同的。因此,要实现上述的jQuery代码见下面。(作者应该已经实现了类似下面的代码)Jsfiddler
$(function(){
function hello(){
var el = $('#user');
el.data('dateOfBirth','1960-10-03');
}
function undIt(){
var el = $('#user');
el.data('dateOfBirth',null);
}
alert($('#user').data('dateOfBirth'))
hello()
alert($('#user').data('dateOfBirth'))
undIt()
alert($('#user').data('dateOfBirth'))
//delete document.querySelector('#user').dataset.dateOfBirth;
//delete $('#user').data('dateOfBirth');
delete jQuery.cache.data.dateOfBirth;
alert($('#user').data('dateOfBirth')) //This line throws Error. Read Note: section
});
的jQuery维护一个名为jQuery.cache缓存变量。数据,并在此引擎下存储键/值,以通过查询DOM并提取值来避免性能开销。如果你想用HTML5实现数据的jQuery的 API使用.Attr() API
注:在上面的代码值被删除,浏览器不能引用不确定最后一行抛出一个错误或null对象树中的对象引用。从技术上讲,变量和引用被删除。
https://api.jquery.com/jQuery.removeData/ –
我不认为'删除$ this.data('counterup-nums');'什么都做不了...... http:// jsfiddle .net/arunpjohny/qdwb5avx/2/ –