如何重置Ajax成功功能? [英] How can I reset an Ajax success function?

查看:90
本文介绍了如何重置Ajax成功功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   $(document).on("click", ".example", function (event) {
        alert("test");
        var id = 1;
        $.ajax({
            url: "update.php",
            data: {
                id: id,
            },
            type: "POST",
            success: function (data) {
                $("#result").html(data); 
            }
        }) 
    });

如果我删除此行...

If I remove this line...

 success: function (data) {
   $("#result").html(data); 
 }

...然后,每次单击仅一次警告测试".

... then "test" is alerted on every click only once.

但是,每当我单击.example按钮时,都在此行中,测试"在更多时间被提醒.

But with this line every time I click on my .example button, "test" is alerted on more time.

所以这意味着:

  • 首先单击->警报测试"
  • 第二次单击->警报测试",警报测试"
  • 第三次单击--->警报测试",警报测试",警报测试"

...等等.

我认为是由于.example按钮也是Ajax之前创建的.

I think it is caused because the .example button was also created by Ajax before.

那么有可能以某种方式重置成功功能吗?

So is there a possibility to reset somehow the success function?

推荐答案

因为您的脚本在每次成功调用时都会一次又一次初始化,所以只需 off()该事件,然后再使用 on()进行,

Because your script is initialised again and again on every success callacks, so just off() the event before using on() like,

$(document).off("click", ".example").on("click", ".example", function (event) {
    alert("test");
    var id = 1;
    $.ajax({
        url: "update.php",
        data: {
            id: id,
        },
        type: "POST",
        success: function (data) {
            $("#result").html(data); 
        }
    }) 
});

这篇关于如何重置Ajax成功功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆