这是一个有趣的情况。从另一个js文件调用ajax删除函数结果

时间:2014-04-13 17:57:08

标签: javascript php ajax autoload

我有一个页面,我使用js和ajax文件自动加载记录(无限滚动)。我想要做的是使用ajax为每条记录添加一个删除功能。

我正常工作的ajax / js功能;但是加载了这个无限滚动记录,我无法正常工作。

我的页面相当复杂,所以这是一个简化版本。

普通的index.php没有ajax删除功能。

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>
带有ajax删除功能的

index.php

<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文件。

1 个答案:

答案 0 :(得分:0)

请注意,您仅在文档就绪时附加了单击处理程序。我假设你的无限滚动解决方案是动态加载新元素。这些新元素没有附加任何点击处理程序。

这个问题有两个解决方案。

  1. 您可以在创建新项目后附加处理程序
  2. 您可以将处理程序附加到dom结构中较高的元素,这是静态的,并听取他孩子的点击事件。要创建这样的处理程序,您应该使用指定了选择器的'on'方法(https://api.jquery.com/on/)。例如:

    $('#parentElement')。on('click','。del-action',function(){// handler});