我有一个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>
我已经尝试了几件事来让它发挥作用。我的第一个想法是,间隔比脚本摆脱最后一个列表项更快,但我已经测试了这个以5000的间隔为get,1000为隐藏/显示元素,这应该提供至少在下次通话之前额外增加3000毫秒。我也试过改变这个:
$("#recentBranches ul li").last().hide(showHideSpeed / 4,
function () {
$("#recentBranches ul li").last().remove();
});
为:
$("#recentBranches ul li").last().remove();
然而,8次后我得到同样的问题。似乎在它进入这种每隔一段时间只能工作的节奏之后,它就会保持不变。我试过看aroudn,但我似乎无法找到能解释这些症状的任何东西......
答案 0 :(得分:3)
您使用错误的斜杠关闭<li>
,这意味着您实际上每个请求添加了2 <li>
个。 (第二个是空白的)
更改此行:
firstLI.before('<li>' + html + '<\li>');
到此:
firstLI.before('<li>' + html + '</li>');