- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想发送在文本字段中键入的击键,但只能以 1 秒的间隔发送。
这是为了减少在每次按键时发送 ajax 请求的负载。
所以例如。如果用户在一秒钟内键入 4 个字母,请求将发送所有这 4 个字母。假设他在 1 分钟内不停地打字,那么脚本将以 1 秒的间隔发送,直到他停止打字。
目前我的脚本是这样的:
$("#type_post").live('keyup', function() {
$.post('posts.php', {post: $("#type_post").val()});
});
但这会发送所有按键。
谁能帮帮我
更新:这是我使用的代码。
var last_post = '';
$('#type_post').focus(function() {
// check if text has been changed every second when input field is focused
setInterval(function() {
if($('#type_post').val() != last_post)
{
// if changed, post it and set the new text as last text
$.post('posts.php', {post: $("#type_post").val()});
last_post = $("#type_post").val();
}
}, 1000);
});
最佳答案
好吧,不管这个功能有多烦人,您都需要使用 setTimeout()
( info here ) 每秒运行一个函数并获取文本。如果不同,则执行 ajax 调用。
除此之外,您只希望在文本框具有焦点时启用此功能,因此您可以在“焦点”和“模糊”事件上设置一个字段和相关操作。
关于javascript - 1秒后用ajax发送击键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2069026/
menu Home Events Technical Schedule
我试图阻止触发默认 anchor 链接和 onclick 事件。 这是 HTML 代码: Google 我正在尝试使用以下 jQuery 代码阻止任何重定向的发生: $("#mylink").cli
我想在单击父 div 上的任意位置时切换我的 div,除非单击 anchor 元素。因此,例如,如果我单击示例中的第一个文本,我希望它切换,但在我的示例中的第二个文本上,我不希望它切换。 JSFidd
我在通过 jQuery 伪造 anchor 点击时遇到问题:为什么我的thickbox在我第一次点击输入按钮时出现,但第二次或第三次却没有出现? 这是我的代码: Link 当我直接点击链接时,它总是
我已经从 Mootools 切换到 jQuery,因为我认为它有更好的支持。我有这样的 HTML: Opcje Opcje Opcje Opcje Opcje Opcje Opcje JS
我是一名优秀的程序员,十分优秀!