我有一个javascript函数,我正试图将它添加到我的文档中,让它有一种实时更新的感觉。这是对MVC控制器的AJAX调用,它返回一个JSON结果并将其添加到列表顶部,然后隐藏最后一个li,然后删除最后一个li。
问题是,这个函数完美地工作了8次,然后就出了问题。在前8次之后,该函数只隐藏列表中的最后一项,每隔一次它就会向顶部添加一项。因此,在前8次运行之后,我的列表每运行一次脚本就会增加1个li:
下面是我的函数:
<script type="text/javascript">
$(document).ready(function () {
function latestBranch() {
$.getJSON("Home/LatestWristband", null, function (html) {
var showHideSpeed = 200;
var firstLI = $("#recentBranches ul li").first();
if (firstLI.text() !== html) {
firstLI.before('<li>' + html + '<\li>');
$("#recentBranches ul li").first().hide().show(showHideSpeed);
$("#recentBranches ul li").last().hide(showHideSpeed / 4,
function () {
$("#recentBranches ul li").last().remove();
});
}
});
};
setInterval(latestBranch, 500);
});
</script>我已经尝试了几种方法来让它工作。我的第一个想法是,时间间隔比脚本删除最后一个列表项的时间间隔要快,但我测试了get的时间间隔为5000,元素的隐藏/显示时间间隔为1000,这应该至少在下一次调用之前提供额外的3000ms。我也尝试过改变这一点:
$("#recentBranches ul li").last().hide(showHideSpeed / 4,
function () {
$("#recentBranches ul li").last().remove();
});至:
$("#recentBranches ul li").last().remove();然而,我在8次之后得到了同样的问题。然而,似乎在它进入这种每隔一次才工作的节奏之后,它会不确定地保持它。我试着四处寻找,但似乎找不到任何可以解释这些症状的东西……
发布于 2011-11-12 10:33:55
您使用了错误的斜杠来关闭<li>,这意味着您实际上为每个请求添加了2个<li>。(第二个为空)
更改此行:
firstLI.before('<li>' + html + '<\li>');要这样做:
firstLI.before('<li>' + html + '</li>');https://stackoverflow.com/questions/8102034
复制相似问题