2011-12-15 70 views
3

需要一些數據存儲在window.load和檢索document.ready在window.load和document.ready中的jQuery數據(),有沒有定義?

<script> 
    $(window).load(function() { // Store here 
     $('img.storable').each(function() { 
     $(this).data("key", "value"); 
     console.log($(this).data("key")); // Output: value 
     }; 
    }; 

    $(document).ready(function() { // Retrieve here 
     $('img.storable').each(function() { 
     console.log($(this).data("key")); // Output: undefined! 
     }; 
    }; 
</script> 

產出document.ready不確定。我是否錯過了關於dom事件的一些事情?

回答

6

$(document).ready()只要DOM加載就運行,但$(window).load()不會運行,直到DOM已經加載並且所有的dom資源已經加載(如圖像和CSS文件和東西)。這意味着$(document).ready()將在您設置該值之前運行。

2

我覺得文件準備情況window.load前... 所以這應該是完全圍繞

其他方式只是做一個簡單的測試:

$(document).ready(function() { 
    alert('document ready'); 
}); 
$(window).load(function() { 
    alert('window load'); 
}); 
相關問題