【问题标题】:Store variable at the time button is clicked for use when ajaxComplete event fires在 ajaxComplete 事件触发时单击按钮时存储变量以供使用
【发布时间】:2015-01-17 22:10:23
【问题描述】:

我在同一个类的页面上有 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);       
    });
});

【问题讨论】:

    标签: javascript jquery ajax javascript-events event-handling


    【解决方案1】:

    我能够将我需要的变量从 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.
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 2014-05-04
      • 2020-02-20
      • 2021-03-02
      • 2022-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多