点击事件运行3次

时间:2014-09-05 02:46:37

标签: javascript jquery get put

我有这个脚本使用GET从我的数据库中获取数据并在HTML中显示它们,然后当我按下复选框时在数据库中更新,但是当我按下复选框时,PUT完成了三次。有谁知道如何解决这个问题?

欢迎任何帮助。

以下代码:

$.ajax({
    type: 'GET',
    async: false,
    url: 'https://app.myapp.com/reservations',
    success:function(reservations){

        reservas.forEach (function (reservation) {
            var HTML = [];


            HTML.push('<tr class="reservations">');
            HTML.push('<td> <input type="checkbox" class="checkbox" data-id="' + reservation._id + '" data-nome="' + reservation.nome + '" data-email="' + reservation.email + '" /> </td>');
            HTML.push('<td>' + reservation._id + '</td>');
            HTML.push('<td>' + reservation.nome + '</td>');
            HTML.push('<td>' + reservation.email + '</td>');
            HTML.push('</tr>');
            $('tbody').append(HTML.join(""));

            $(function(){
                $(document).on('click', '.checkbox', function(){
                    console.log('salvo');
                    var update = $(this);


                    $.ajax({

                        type: 'PUT',
                        url: 'https://localhost/datas',
                        data: {
                            _id: update.attr('data-id'),
                            nome: update.attr('data-nome'),
                            email: update.attr('data-email'),
                        },
                        sucess:function (success) {
                            alert('updated!!');
                        },
                        error:function(err) {
                            console.log(err);
                        }
                    });
                });
            });
        })
    },
    error:function(e){
        console.log(e);
    }
});

2 个答案:

答案 0 :(得分:1)

您正在另一个请求的成功事件中全局分配您的点击处理程序。它也在foreach循环中。要解决这个问题,请将点击处理程序分配移到成功处理程序之外,并移出任何循环。

答案 1 :(得分:1)

问题是您是在每次迭代时添加事件。 你应该从那个.each中获取Event监听器功能。 当您在文档本身上使用jQuery函数时,您可以将该事件侦听器完全从您的ajax函数中取出,它将会正在监听复选框上的单击(因为,如上所述,您将事件绑定到文档而不是复选框本身,因此在绑定事件之前不需要它们存在。)