2012-11-30 28 views
2

我用這個簡單的jQuery代碼從一個div獲得元素,然後以感謝其更改爲一個PHP腳本:Jquery:我如何檢測內容更改? (尋找替代KEYUP())

$(document).ready(function(){ 
    $("#description").keyup(function(){ 
    var recherche = $(this).val(); 

    $.ajax({ 
     type : "GET", 
     url : "result.php", 
     data : {motclef: recherche}, 
     success: function(server_response){ 
     $("#resultat").html(server_response).show(); 
     } 
    }); 
}); 

}); 

問題是有些變化,而不按happend任何鍵(複製/過去...)。我已經嘗試過.change(),但只有當元素的焦點丟失時纔會觸發它。

+0

你跟蹤值和比較他們 – kidwon

+0

'input'事件是你想要的。 – pimvdb

+1

您可能想要考慮延遲AJAX調用,以便在發送請求之前按鍵之間必須有一定的時間延遲;每個'keyup'事件發送一個請求可能會導致很多請求被髮送。 –

回答

1

你可以告訴jQuery在一次調用中綁定多個事件。 進入方法後,您可以根據事件類型篩選行爲。在處理粘貼時,稍微延遲一下函數調用通常是一個好主意,以允許瀏覽器首先完成所需的任何操作。

編輯

我已經更新,以處理自動完成基於這個計算器answer答案。

$("#description").on("keyup paste cut focus change blur",function (event) { 

    var $this = $(this), 
     delay = 0 

    // Add delay for cut/paste 
    if (event.type === "paste" || event.type === "cut") { 
     delay = 5; 
    } 

    // Record the current value of the text box. 
    if (event.type === "focus" || event.type === "change") { 
     this.previousvalue = this.value; 
    } 

    // Trigger the change event if the value is now different. 
    if (event.type === "blur") { 
     if (this.previousvalue !== this.value){ 
      $this.change(); 
      return false; 
     } 
    } 

    window.setTimeout(function() { 

     var recherche = $this.val(); 

     $.ajax({ 
      type : "GET", 
      url : "result.php", 
      data : {motclef: recherche}, 
      success: function(server_response){ 
       $("#resultat").html(server_response).show(); 
      } 
     });     

    }, delay); 
}); 
+0

謝謝,但實際上我複製過去不是唯一的問題,我也使用了一個autocompleter,你知道我可以如何將它包含到你的代碼? – user1836529

+0

我已經更新了我的答案。注意這一切都未經測試。 –

+0

謝謝我嘗試過,但它不起作用,我什麼也沒有出現。 – user1836529