【问题标题】:jQuery runtime ready event after loading another page加载另一个页面后的 jQuery 运行时就绪事件
【发布时间】:2013-06-26 20:07:09
【问题描述】:
var x = $("<div ></div>");
$('body').append(x);
x.load('page.html'
    , function() {
        $(document).ready(
            function (){
            //useful stuff here;
            }
        );  
    });

我希望在 page.html 完全加载并已执行我的“div”中的所有脚本之后执行准备好的回调函数。
这个例子有效。
我的问题是:这是做我所期望的正确方法吗?还有其他方法吗? 在这种情况下,就绪事件背后的逻辑是什么?它应该应用于“document”、“this”还是“x”?

【问题讨论】:

  • 为什么? x.load('page.html', function(){//dostuff});有什么问题吗?
  • 当您希望在 page.html 的 ready() 上执行就绪后执行脚本时可以正常工作

标签: jquery events document-ready


【解决方案1】:

你的加载事件应该被封装在DOM ready ..

$(document).ready(function () {
    var x = $("<div ></div>");
    $('body').append(x);
    x.load('page.html', function () {

        //useful stuff here;
    });
});

不需要将回调包含在DOM ready handler..

它适用于这种情况,因为您似乎没有选择页面上任何现有的元素。所以它可以在没有DOM ready 处理程序的情况下正常工作

【讨论】:

  • 如果你想在 page.html 上的 jquery 脚本之前执行脚本可以正常工作,但是如果你想在 page.html 的 jquery 脚本 $(document)ready(...) 之后执行你的例子没有正常工作.
  • @Sushanth 我的“有用的东西”应该在 page.html 中的所有脚本完成运行后执行。当使用加载回调时,如您的示例所示,它将在 page.html 中的脚本之前开始运行。这不是我所期待的。
【解决方案2】:

dummy.html

<SCRIPT>
    $(document).ready(
        function(){
            var x = $("<div >hola</div>");
            $('body').append(x);
            x.load('dummy2.html', function() {

                console.log('dummy callback');

                $(document).ready(
                    function (){
                    console.log('dummy has loaded after dummy2 has loaded');
                    //useful stuff here;
                    }
                );
            });
        }
    );
</SCRIPT>

dummy2.html

 <SCRIPT>
    $(document).ready(
        function(){
            console.log('dummy 2a has load');
        }
    );
    $(document).ready(
        function(){
            console.log('dummy 2b has load');
        }
    );


</SCRIPT>

这个例子展示了如何处理这个序列,首先打印 dummy callback',第二个:dummy 2a 和 dummy 2b,最后一个打印是 'dummy has loaded after dummy has loaded',我知道为什么可以正常工作,但是序列工作正常。

更新

如果删除 $(document).ready 行,则序列为

first:虚拟回调 第二:dummy 已加载... /错误!/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2013-08-05
    • 2011-07-20
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多