1

这是我的代码:

// Refresh feeds, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
    $("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });

我正在开发一种类似于 Facebook 的“墙”,您可以在其中评论彼此的帖子。墙会自动使用 AJAX 刷新(每 9 秒),但是当您键入并且文本字段被聚焦时,它会在页面刷新后移除焦点和文本框的内容。

我怎样才能让它只在你不打字时刷新,在你打字时让它停止。谢谢!我到处寻找并尝试了一切,但没有运气。

4

2 回答 2

2

我想你有一个这样的输入框:

<input type="text" id="input-box" ... />

您所要做的就是维护一个全局变量,而不是说这个输入是否具有焦点:

var isTyping = false;
$("#input-box").focus(function() {
    isTyping = true;
});
$("#input-box").blur(function() {
    isTyping = false;
});

那么你只需要在允许更新之前检查这个变量:

// Refresh feeds, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
    if (!isTyping) {
        $("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
}, 9000);
    }
$.ajaxSetup({ cache: false });
于 2011-08-30T22:29:56.760 回答
0

timeout您应该在他们键入时保持计时器运行,并在加载之前检查:

var typing = false,
    theTimer,
    refreshId = setInterval(function() {
        typing || $("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
    }, 9000);
$.ajaxSetup({ cache: false });

$('#theInput').keyup(function() {
    typing = true;
    theTimer && clearTimeout(theTimer);

    theTimer = setTimeout(function() {
        typing = true;
    }, 500);
});
于 2011-08-30T22:28:49.117 回答