【问题标题】:jQuery data() in window.load and document.ready, got undefined?window.load 和 document.ready 中的 jQuery data() 未定义?
【发布时间】:2011-12-15 01:20:10
【问题描述】:

需要在window.load中存储一些数据并在document.ready中检索:

<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 事件的信息?

【问题讨论】:

    标签: javascript jquery dom javascript-events


    【解决方案1】:

    $(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');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-26
        • 2012-01-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2012-08-29
        • 1970-01-01
        相关资源
        最近更新 更多