在 jQuery on 函数中同时对多个项目运行时保持一致的值

Keeping a value consistent In jQuery on function when run on multiple items at the same time

本文关键字:项目 运行时 保持一致 on jQuery 函数      更新时间:2023-09-26

我正在编写一个模块,其中包含用户可以选择回答的多个问题。 每个按钮都有自己的提交按钮,用于将数据发布到我的应用程序,显示结果,然后删除表单。 我能够让这篇文章完美地工作,但是如果我添加一个按钮,允许用户一次提交所有表单,它会正确提交表单数据,但结果会附加到最后一个问题(项目正在获取正确的数据(。 这是我正在使用的javascript/jQuery代码:

// setup the save answer click handler
$(document).on('click', '.saveAnswer', function(event){
    event.preventDefault();
    // get the form
    form = $(this).closest('form');
    $.ajax({
        async:true,
        type: 'POST',
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data){
            // append the text to the bottom of the answers
            form.closest('.question').find('.answers').append('<li>' + data + '</li>').hide().slideDown(500);
            form.slideUp(500,function(){
                form.remove();
            });
        }
    });
});
// setup the save all answer click handler
$(document).on('click', '.saveAll', function(){
    $('.saveAnswer').trigger('click');
});

如果我将async值更改为 false,那么它可以正常工作,但没有任何动画工作,页面似乎冻结了一秒钟,直到提交所有答案。

经过一些调试,我发现每次运行函数时都会覆盖form变量。 有没有办法防止这种情况发生?

form是一个全局(或至少是更高范围的(变量,这意味着对处理程序的每次调用都会践踏旧值,并且success/error回调都共享相同的值。

使其成为本地 ( var form = $(....); (,以便处理程序的每个调用都有自己的值。

以防万一,如果你不想改变变量的范围,你可以使用闭包来存储表单变量,就像这样

form = $(this).closest('form');
$.ajax({
        .....
        success:(function (formClosure) {
            return function(data){ 
            // for this function formClosure will be local variable, 
            // so changing form variable doesn't take effect
            formClosure.closest('.question').find('.answers').append('<li>' + data + '</li>').hide().slideDown(500);
            formClosure.slideUp(500,function(){
                form.remove();
            });
          };
        })(form)
    });