【问题标题】:Dynamic load page with scripts带有脚本的动态加载页面
【发布时间】:2015-09-23 10:04:31
【问题描述】:

如果我使用 jquery 函数 $.load 从服务器(ASP.net 部分视图)获取一些内容并将其加载到 div 中,并且如果该内容具有以下内容:

<script>
$(document).ready(function () {
     some code block
})
</script>

内容加载到div后,代码块会被执行,会触发ready事件吗?

【问题讨论】:

  • no.. 因为您来自服务器的响应数据没有自己的 dom。
  • @RohitKumar OP 说:来自服务器的内容(ASP.net 部分视图)并将其加载到 div 中

标签: javascript jquery ajax


【解决方案1】:

在包含脚本标签的Ajax调用中,所有发送的脚本都会在插入到文档对象模型后执行。

但是在您的情况下,脚本标记包含事件分配,因此事件分配将执行,但是为什么在插入到文档对象模型后执行分配的函数而未引发就绪事件? 发生这种情况的原因是:

总结:

Ready 仅类似于 event 但不是真正的一个 event,它是 Pseudo-Event。

详细

以下代码是jquery库的来源:

jQuery.fn.ready = function( fn ) {

    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

你看到 ready 是一个获取函数的 jQuery 插件。在函数体中说当就绪事件完成时执行发送函数。但是当就绪时完成。再次查看 JQuery 源代码:

jQuery.extend( {

    // Is the DOM ready to be used? Set to true once it occurs.
    isReady: false,

    // A counter to track how many items to wait for before
    // the ready event fires. See #6781
    readyWait: 1,

    // Hold (or release) the ready event
    holdReady: function( hold ) {
        if ( hold ) {
            jQuery.readyWait++;
        } else {
            jQuery.ready( true );
        }
    },

    // Handle when the DOM is ready
    ready: function( wait ) {

        // Abort if there are pending holds or we're already ready
        if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
            return;
        }

        // Remember that the DOM is ready
        jQuery.isReady = true;

        // If a normal DOM Ready event fired, decrement, and wait if need be
        if ( wait !== true && --jQuery.readyWait > 0 ) {
            return;
        }

        // If there are functions bound, to execute
        readyList.resolveWith( document, [ jQuery ] );
    }
} );

加载文档对象模型的以下行集已完成:

// Remember that the DOM is ready
jQuery.isReady = true;

所以如果 Jquery.isReady == true,传递给 ready 方法的函数会立即执行。

所以为在就绪状态下运行的脚本提供了就绪方法,而不是就绪事件。

【讨论】:

    【解决方案2】:

    在文档为"ready." 之前,无法安全地操作页面 jQuery 会为您检测到这种准备状态。包含在 $( document ).ready() 中的代码只会在页面文档对象中运行一次 模型 (DOM) 已准备好执行 JavaScript 代码。包含代码 内部$( window ).load(function() { ... }) 将运行一次整个 页面(图像或 iframe),而不仅仅是 DOM,已准备就绪。

    所以,是的,只有在你的 dom 完全加载后,你的代码才会被执行。

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多