dsdfd2322 2016-05-23 03:58
浏览 251
已采纳

JQuery load()使Jquery函数多次触发

This is my code. It loads the pages content without refresh.

The problem is when I click on button handled by jQuery and ajax it fires as many times as I load the pages.

For e.g. If loaded 2 pages, jQuery will fire twice

If I loaded 4 pages, jQuery will load 4 times.

 <script>
        $(document).ready(function(){
            //set trigger and container

            var trigger = $('#nav ul li a'),
                container = $('#container');
            //do on click


            trigger.on('click', function(e){
                /***********/
                 e.preventDefault();

               /* reload content without refresh */
                //set loading img
                $('#container').append('<div id = "loading">WAIT...  <img src = "img/ajax-loader-small.gif" alt="Currently loading"   /></div>');
                //change img location to center
                $("#loading").css({"position": "absolute", "left": "50%", "top": "50%"});
                //get the  trigger to reload the contents
                var $this = $(this),
                    target = $this.data('target');

                container.load(target + '.php');

              //  return false;
                $(trigger).die('click');
            });
        });

This script fires as many times as I load the page through load() function which mean same post will be inserted many times into the database

<script>

    $(document).ready(function(){


    $(document).on("click",".fa-pinterest-square",function(e) {


        var form = $(this).find('form'); //Since the form is child to <i>

        $.ajax({
            url: "includes/widgets/add_pains.php",
            type: "POST",
            data: form.serialize(),
            success: function(data) {
                alert(data);

            }
        });

    });
    });

</script>

How can I fix this issue?

  • 写回答

3条回答 默认 最新

  • dongmei8460 2016-05-23 04:01
    关注

    This happened because you didn't clear the event listener each time you load the script and the event listener stacked on each other caused trigger multiple times.

    trigger.off('click').on('click', function(){....})
    

    The .off() method removes event handlers that were attached with .on().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝