2011-08-23 149 views
2

http://jsbin.com/ezecun/edit#javascript,htmlonkeyup方式太慢

我必須這樣寫,因爲它是動態製作的,下面列出的實際代碼。我在jsbin中簡化了一下。基本上它需要很長的時間來更新數組,使其不可用。

感謝您的關注。

CODE: PHP

echo "<label style='float:left'>Comments: </label> <textarea onKeyUp=\"editItemInCart(this.value,'comments',".$itemNum.")\" onChange=\"editItemInCart(this.value,'comments',".$itemNum.")\" >".$cart['comments']."</textarea><br />"; 

的JavaScript

function editItemInCart(newValue,fieldName,itemNum) { 
    jQuery.ajax({ 
     type:"POST", 
     url: "editItem.html", 
     data: "newvalue=" + newValue + "&fieldname=" + fieldName + "&itemNum=" + itemNum, 
    }) 
    //alert(newValue + fieldName + itemNum); 
} 
+0

你對此有何看法? –

+2

這不是關鍵事件,但腳本必須等待服務器響應AJAX查詢。您是否測量了editItem.html處理查詢需要多長時間? – JJJ

+0

我希望它使用基於這兩個事件的新值更新數組。 頁面不到一秒鐘,沒問題。我認爲在等待不活動的時候增加一個延遲,然後更新會更好,所以它不會一直髮射。 – oneadvent

回答

2

你真的想張貼在每個類型的鍵或當用戶輸入完?在處理一封信之前,大多數人可以輸入整個單詞。你需要一個計數。事情是這樣的:根據您的意見

var count = 0; 
function doEditItemInCart(newValue,fieldName,itemNum) 
{ 
    count++; 
    setTimeout("editItemInCart('"+newValue+"','"+fieldName+"',"+itemNum+","+count+")",200); 
} 
function editItemInCart(newValue,fieldName,itemNum,cnt) { 
if (count == cnt) { 
     count = 0; 
     jQuery.ajax({ 
      type:"POST", 
      url: "editItem.html", 
      data: "newvalue=" + newValue + "&fieldname=" + fieldName + "&itemNum=" + itemNum, 
     }) 
     //alert(newValue + fieldName + itemNum); 
    } 
} 
+0

好的,這個效果好多了,它仍然是一個延遲,只是沒有那麼糟糕。我想我需要在某處放置一個「保存」的分區,以便客戶知道。已標記回答。 – oneadvent

0

,這聽起來像你想的debounce事件keyup。我推薦Ben Alman的jQuery throttle/debounce plugin

var itemNum = $('#item_num_id').val(); 
$('#textarea_id').keyup($.debounce(250, editItemInCart(this.value,'comments', itemNum))); 

上述代碼消除了內聯事件處理程序,使您可以很好地區分標記和代碼。

+0

我真的不想添加另一個庫,即使是一個小庫。我標記的答案使用了我已有的代碼。雖然謝謝! – oneadvent