2015-07-13 91 views
2

我只是通過代碼將在counterup.js,我碰到下面的代碼行:理解爲什麼數據屬性值都設置爲null

  delete $this.data('counterup-nums'); 
      $this.data('counterup-nums', null); 
      $this.data('counterup-func', null); 

當然這個插件使用的數據存儲屬性值,它稍後用於計算。現在我的問題是,不是上面的代碼行是什麼,而是爲什麼上面的代碼行呢?

確定的第一行代碼:

delete $this.data('counterup-nums'); 

是否看得懂一點點,但什麼是代碼的下方線條可言

$this.data('counterup-nums', null); 
$this.data('counterup-func', null); 

在做什麼?

+0

https://api.jquery.com/jQuery.removeData/ –

+2

我不認爲'刪除$ this.data('counterup-nums');'什麼都做不了...... http:// jsfiddle .net/arunpjohny/qdwb5avx/2/ –

回答

3

這很有趣。但我通過編寫如下示例代碼研究了一些有趣的事實。

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樹仍然存在(設置爲未定義字符串)看到下面的圖片enter image description here

當我取消評論刪除聲明我可以看到它已從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對象樹中的對象引用。從技術上講,變量和引用被刪除。

+0

謝謝!將會通過你的代碼,一旦我回家 –

+0

@Nirus注意,jQuery'.data()'https://api.jquery.com/data/不依賴於'HTMLElement.dataset' https://developer.mozilla .org/en-US/docs/Web/API/HTMLElement/dataset;兩個獨立的實現? – guest271314

+1

@ guest271314通過根據您的評論做更多的研究更新了答案。希望能幫助到你。 – Nirus

1

delete:刪除操作從對象中刪除屬性。

我可能沒有解釋delete $this.data('counterup-nums');行正在做什麼,但可能是作者想要用這行清除所有的東西。我相信這delete關鍵字與$this.data('counterup-nums')沒有意義。代替這delete我會更喜歡Jquery.removeData()從元素中刪除data屬性。

但以下做一樣的感覺:

$this.data('counterup-nums', null); 
$this.data('counterup-func', null); 

作者是設置數據屬性null,這樣下次他可以輕鬆地識別,值復位與否。

相關問題