繁体   English   中英

如何重启JS功能?

[英]How to restart JS function?

我有一个“喜欢”按钮的脚本。 当我单击按钮时,AJAX将数据发送到videolike.php

  1. 首先,我使用限制为10的 PHP从数据库中获取视频

  2. 加载此脚本后...

     <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> 

现在我的主页上有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>

您将要使用委托事件处理程序。

这将附加一个侦听器,并将单击的目标与选择器(在这种情况下为.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()的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM