如何重启JS功能?

时间:2017-06-12 15:04:41

标签: javascript php jquery ajax

我有一个脚本,用于"喜欢"按钮。当我点击按钮时,AJAX将数据发送到 videolike.php

  1. 首先,我使用PHP 限制10

  2. 从数据库获取视频
  3. 此后加载此脚本......

    <script type="text/javascript">
         $(".vidlike").click(function() {
         var form = $(this).closest(".vidlikform");
    
         $.ajax({
              type: 'post',
              url: "functions/videolike.php",
              data: form.serialize(), // serializes the form's elements.
              success: function(data)
              {
                  alert(data); // show response from the php script.
              } 
         });
         return false; // avoid to execute the actual submit of the form.
    });
    </script>
    
  4. 现在我的主页上有10个视频,脚本运行正常。将数据发送到 videolike.php 而不重定向...

    问题是这个脚本仅适用于前10个视频,而且它不适用于我从数据库获取的下一个视频,将我重定向到 videolike.php ...

    这是我用来获取更多数据的脚本:

    <img class="load-more" id="<?php echo @$var['video_id']; ?>" src="img/loader.gif"/>
    
    <script type="text/javascript">
        //Ajax more data load Home page
        $(document).ready(function(){
            $(window).scroll(function(){
                var lastID = $('.load-more').attr('id');
                if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
                    $.ajax({
                        type:'POST',
                        url:'functions/getData.php',
                        data:'id='+lastID,
                        beforeSend:function(html){
                            $('.load-more').show();
                        },
                        success:function(html){
                            $('.load-more').remove();
                            $('#main').append(html);
                        }
                    });
                }
            });
        });
    
        </script>
    

1 个答案:

答案 0 :(得分:0)

您将需要使用委派的事件处理程序。

这将附加一个侦听器,并将单击的目标与选择器进行比较,在本例中为.vidlike

即使您通过添加更多结果来修改DOM,这也会有效。

$('body').on("click", ".vidlike", function() {
     var form = $(this).closest(".vidlikform");

     $.ajax({
          type: 'post',
          url: "functions/videolike.php",
          data: form.serialize(), // serializes the form's elements.
          success: function(data)
          {
              alert(data); // show response from the php script.
          } 
     });
     return false; // avoid to execute the actual submit of the form.
});

有关详细信息,请参阅.on()的文档。