【问题标题】:onkeyup way too slowonkeyup 太慢了
【发布时间】:2011-08-23 21:08:14
【问题描述】:

http://jsbin.com/ezecun/edit#javascript,html

我必须这样写,因为它是动态生成的,下面列出了实际代码。我在 jsbin 中对其进行了一些简化。基本上用不可用的框的值更新数组需要很长时间。

感谢观看。

代码: 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);
}

【问题讨论】:

  • 你希望这会做什么?
  • 慢的不是keyup事件,而是脚本要等待服务器响应AJAX查询。您是否测量过 editItem.html 处理查询需要多长时间?
  • 我希望它根据那里的两个事件用新值更新一个数组。页面不到一秒,没问题。我认为添加一个等待不活动然后更新的延迟会更好,所以它不会一直触发。
  • 一个完整的往返 HTTP 请求将需要(比如说)1 秒。我什至可以在同一时间段内敲出至少 5 或 6 个字符。这意味着您之前的 ajax 请求将忙于处理现在完全陈旧的数据,因为它们至少有 5 或 6 个字符已过期。

标签: php javascript jquery ajax onkeyup


【解决方案1】:

您真的想在每个键入的键上或在用户完成键入时发布吗?大多数人可以在处理一个字母之前输入一个完整的单词。你需要一个计数。像这样的:

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);
    }
}

【讨论】:

  • 好吧,这效果更好,它仍然是一个延迟,只是没有那么糟糕。我想我需要在某个地方放置一个“已保存”的 div,以便客户知道。标记为已回答。
【解决方案2】:

根据您的 cmets,听起来您想要 debounce keyup 事件。我推荐 Ben Alman 的 jQuery throttle / debounce plugin

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

上面的代码消除了内联事件处理程序,使您可以很好地分离标记和代码。

【讨论】:

  • 我真的不想添加另一个库,即使是一个小的库。我标记的答案使用我已经拥有的代码。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-03-10
  • 2014-06-07
  • 2016-05-31
  • 2011-07-07
  • 2015-08-23
  • 2012-07-05
  • 2016-01-08
  • 2014-03-12
相关资源
最近更新 更多