因此,我通过名为 ajaxLoad.php 的文件中的 foreach 循环向 index.php 添加元素,该文件是使用 jQuery 的 load() 加载的。
问题是当我尝试选择这些元素时,jQuery 无法找到它们。我知道 ajaxLoad.php 尚未完成打印消息。当我尝试使用 jQuery 选择删除类 anchor 时,jQuery 找不到它们。
<div class="messages">
<!--these are added by the foreach loop-->
<a href="#" class="delete">Delete</a>
</div>
一个可能重要的注意事项是删除类不在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(){}) 但它似乎不起作用。 我很乐意提供帮助!谢谢!
最佳答案
放在回调函数中,见manual :
$('.messages').load('ajaxLoad.php', function() {
$('.delete').click(function(){
alert('Hey');
});
});
或者使用event delegation :
$('.messages').load('ajaxLoad.php');
//later on...
$('body').on('click', '.delete', function() {
// ^^^^ any containing element that is already there on page-load
alert('Hey');
});
关于javascript - 如何在继续脚本之前有效地等待链接文件完成运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234113/