如何有效地等待链接文件在继续运行脚本之前完成运行


How to efficiently wait for a linked file to finish running before continuing with script

所以我添加元素到index.php通过foreach循环在一个名为ajaxLoad.php的文件,这是使用jQuery的load()加载。

问题是,当我试图选择这些元素时,jQuery找不到这些元素。我知道ajaxload。php还没有打印完消息。当我尝试用jQuery选择删除类锚时,jQuery找不到它们。

            <div class="messages">
                <!--these are added by the foreach loop-->
                <a href="#" class="delete">Delete</a>
            </div>

一个可能重要的注意事项是,delete类不在index.php标记中,它们只是通过load()添加的。下面是内联jQuery:

<script>
$(function(){
    //adds messages to a div
    $('.messages').load('ajaxLoad.php');
    //later on...
    $('.delete').click(function(){
        alert('Hey');
        //nothing happens
    });
});
</script>

我已经看过$(window).load(function(){}),但它似乎不起作用。我很乐意帮忙!谢谢!

放到回调函数中,参见手册:

$('.messages').load('ajaxLoad.php', function() {
    $('.delete').click(function(){
        alert('Hey');
    });
});

或者使用事件委托:

$('.messages').load('ajaxLoad.php');
//later on...
$('body').on('click', '.delete', function() {
// ^^^^ any containing element that is already there on page-load
    alert('Hey');
});