单击“在时间存储变量”按钮,以便在触发 ajaxComplete 事件时使用

Store variable at the time button is clicked for use when ajaxComplete event fires

本文关键字:ajaxComplete 事件 存储 时间 变量 单击 按钮      更新时间:2023-09-26

我在具有相同类的页面上有 4 个按钮。当单击这些按钮中的任何一个时,都会触发一个 Ajax 事件,我用 ajaxComplete 侦听该事件。问题是,如果我紧接着单击一个按钮,分配给第一个按钮的变量似乎会覆盖第二个按钮,因此不会发生用于第二个按钮的操作。

我附加了特定于元素的命名空间来分隔 ajaxComplete 处理程序,但这并没有解决问题。我可能缺少或没有使用明显的东西。

在我看来,主要问题是我根据单击的最后一个按钮存储 ID,因此当触发事件时,它会影响错误的元素。(分配给$sheetBlock的最新变量)。我需要在单击与事件对应的按钮时存储这些变量。

一些警告 - 我无法向 html 元素添加任何额外的属性,但是,受影响的每个按钮和元素都有自己的 ID。

我认为将$flippyFunc函数存储在 var 中并在按下每个按钮时运行,这将允许我在单击每个按钮时存储每个按钮的 ID,同时单击每个 ajax 事件以一起使用。我该怎么做?

var $id = null;
var $laddaButtons = [];
var $it = null;
var $results = [];
var $sheetBlock = [];
var runOnAjax = function(button, id){
    $(button).off('mousedown.button');
    $sheetBlock[id] = $('#'+button.parentNode.parentNode.parentNode.parentNode.id);
};
var $flippyFunc = function($id){
    $sheetBlock[$id].flippy({
    //options
    });
};
$('.ladda-button').on('mousedown.this', function(e) {
    $id = this.id;
    $it = this;
    runOnAjax($it, $id);
    $(document).on("ajaxComplete."+$id, function(e) {
        $(document).off("ajaxComplete."+$id);
        $flippyFunc($id);       
    });
});

我能够将我需要的变量从 ajaxSend 事件的设置对象传递到相应的 ajaxComplete 事件的设置对象。它就像:

$(document).on("ajaxSend"), function(e, xhr, settings) {
    settings.buttonID = $id;
}

然后在触发相应的 ajaxComplete 事件时访问 buttonID 变量:

$(document).on("ajaxComplete"), function(e, xhr, settings) {
    $id = settings.buttonID;
    // Now I can use `$id` as it was when the ajaxSend event was triggered.
}