gpt4 book ai didi

Javascript 函数正确运行 8 次,然后每隔一次

转载 作者:行者123 更新时间:2023-11-29 10:52:13 25 4
gpt4 key购买 nike

我有一个 javascript 函数,我正试图将其添加到我的文档中,以使其具有实时更新的感觉。这是对我的 MVC Controller 的 AJAX 调用,它返回一个 JSON 结果并将其添加到顶部的列表,然后隐藏最后一个 li,然后删除最后一个 li。

问题是,该功能完美运行了 8 次,然后就出现问题了。在前 8 次之后,该函数只隐藏列表中的最后一项,每隔一次它在顶部添加一个。因此,在前 8 次运行之后,我的列表每隔一次运行脚本就会增长 1 里:

这是我的功能:

<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 的获取间隔和 1000 的隐藏/显示元素测试了它,这应该提供一个至少在下一次通话前额外 3000 毫秒。我也试过改变这个:

$("#recentBranches ul li").last().hide(showHideSpeed / 4,
function () {
$("#recentBranches ul li").last().remove();
});

到:

$("#recentBranches ul li").last().remove();

但是我在 8 次后遇到了同样的问题。似乎进入了这种隔一段时间才工作的节奏之后,就一直保持下去了。我试过四处寻找,但我似乎找不到任何可以解释这些症状的东西......

最佳答案

您使用了错误的斜杠来关闭 <li> ,这意味着您实际上是在添加 2 <li>每个请求。 (第二个是空白)

改变这一行:

firstLI.before('<li>' + html + '<\li>');

为此:

firstLI.before('<li>' + html + '</li>');

关于Javascript 函数正确运行 8 次,然后每隔一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8102034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com