2016-12-02 68 views
2

我有我從一個數據庫表中的信息填充一個HTML表格。我做了細胞的表後點擊編輯和添加的jQuery趕上當電池完成正在編輯(最後一次按鍵後2.5秒),阿賈克斯然後發送信息到一個單獨的PHP文件與變化來更新數據庫表值。我發現的一個問題是,如果電池被點擊了的進入另一個細胞和那些2.5秒是之前做出改變,第一個變化是永遠不會更新到數據庫。jQuery,使用多個事件觸發器?

我的問題是:如果我改爲使用field blur事件,是否還有一種方法可以將定時器合併,以便在達到字段模糊或超時時達到ajax?

$('td').on('input', function() { 
    var _this = $(this); // preserve reference to the input field here 

    if(saveTimeout) clearTimeout(saveTimeout); 
    saveTimeout = setTimeout(function() { 
     console.log(_this) 
     $.ajax({ 
      method: "POST", 
      url: "updatedatabase.php", 
      data: { 
       content: _this.text(), 
       date: _this.siblings().first().text(), 
       prod: $('tr:first-child th:nth-child(' + (_this.index() + 1) + ')').text(), 
       old: old 
      } 
     }) 
     .done(function(msg) { 
      alert(msg); 
     }); 

    }, 2500); 
}); 
+0

是的。您可以在鍵盤上使用計時器,並且可以在單元格上使用模糊。相反,我可能會在首先取消超時的字段中的輸入上執行一個'keyup'事件,然後使用其中的函數運行超時。然後模糊事件添加到字段由'keyup' – ntgCleaner

回答

1

我建議你使用一個不同的.setTimeout延遲取決於哪個事件觸發它。

因此在blur上,它不會等待2.5秒來保存,就像input一樣。

EDITED
爲了防止 「雙節省」,標誌着作爲td保存。

var saveTimeout; 

// Remove the "saved" class on keydown 
$('td').on('keydown', function(e) { 
    $(this).removeClass("saved"); 
}); 

$('td').on('input blur', function(e) { 
    console.log("event "+e.type+" occured"); 
    var timeoutDelay=2500; 

    if(e.type == "blur"){ 
     timeoutDelay=1; 
    } 

    // If NOT already saved... 
    if(!$(this).hasClass("saved")){ 
     var _this = $(this); // preserve reference to the input field here 

     clearTimeout(saveTimeout); 
     saveTimeout = setTimeout(function() { 
      console.log(_this); 

      $.ajax({ 
       method: "POST", 
       url: "updatedatabase.php", 
       data: { 
        content: _this.text(), 
        date: _this.siblings().first().text(), 
        prod: $('tr:first-child th:nth-child(' + (_this.index() + 1) + ')').text(), 
        old: old 
       } 
      }) 
      .done(function(msg) { 
       alert(msg); 
       // Add the "saved" class to prevent other saving 
       _this.addClass("saved"); 
      }); 

      console.log("Ajax sent"); 

     }, timeoutDelay); 
    } 
}); 
+0

該解決方案看起來很有趣作出運行相同的功能,但如果最後'td'不點擊出來的,輸入模糊事件絕對不會發生是否正確?這就是爲什麼我希望定時器,所以我抓住的人誰沒有點擊出來也 – Brandon

+1

輸入,定時器仍然工作......所以,如果不點擊出來,或者如果沒有輸入,也不會保存。 –

+0

哦,我很抱歉,我沒有意識到,直到再次查看輸入和模糊是單獨的事件。我覺得現在很笨... LoL – Brandon