我有一个页面,在那里我使用js和ajax文件自动加载记录(无限滚动)。我想做的是使用ajax为每条记录添加一个删除功能。
我使用的ajax/js函数工作正常;但是加载了这个无限滚动记录,我很难让它正常工作。
我的页面看起来相当复杂,所以这里是一个简化版本。
没有ajax删除功能的普通index.php
ajaxload.php // this is the file with query that loads the results of infinitescroll
<html>
<head>
<title>Home page</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="js/infinitescroll.js"> </script>
</head>
</html>
<body>
<div id="results">
// results of infinitescroll/ajaxload go here. For eg.
<div id="record">
<h1>Title of record</h1>
<p>Post description</p>
<a href="delete.php" id="32">Delete</a>
</div>
</div>
</body>
</html>
index.php带有ajax删除功能
<html>
<head>
<title>Home page</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="js/infinitescroll.js"> </script>
<script>
$(document).ready(function() {
$(".del-action").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
$.ajax({
type: "GET",
url: "delete.php",
data: {id: id},
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
}
});
return false;
});
});
</script>
</head>
</html>
<body>
<div id="results">
// results of infinitescroll/ajaxload go here. For eg.
<div id="record">
<h1>Title of record</h1>
<p>Post description</p>
<a class="del-action" href="#" id="32">Delete</a>
</div>
</div>
</body>
</html>
当我尝试删除该记录时,不会出现任何错误。它只是不调用delete.php文件。
请注意,您只在文档就绪时附加点击处理程序。我假设您的无限滚动解决方案是动态加载新元素。这些新元素没有附加任何单击处理程序。
这个问题有两种解决办法。
- 您可以在创建新项后附加处理程序
-
您可以将处理程序附加到dom结构中较高的元素,该元素是静态的,并侦听其子级的单击事件。若要创建这样的处理程序,应使用"on"方法(https://api.jquery.com/on/)指定了选择器。例如:
$('#parentElement').on('click','.del-action',function(){//handler});