這很有趣。但我通過編寫如下示例代碼研究了一些有趣的事實。
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/ –