我不确定为什么我的函数只能正常运行一次。基本上在我的 JSON 中,GhStatus 和 CsStatus 的值均为 0,因此我预计警报会发出两次“崩溃”消息。
但是,这组警报仅发生一次。然后根据 Chrome 开发者工具,我每 2 秒就会收到错误消息:
Uncaught SyntaxError: Unexpected identifier
但是,输出并未指出代码中发生这种情况的位置=[
$(document).ready(GrabGhCsStatus());
function GrabGhCsStatus() {
var url = '@Html.Raw(Url.Action("index","GhCs"))';
window.setInterval(
$.get(url,function(data) {
if (data.GhStatus == 0) {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'myapp-cs' });
alert('crash');
}
else {
$('#GhCsStatus_GH').buttonMarkup({ icon: 'myapp-gh' });
alert('running');
}
if (data.CsStatus == 0) {
$('#GhCsStatus_CS').buttonMarkup({ icon: 'myapp-cs' });
alert('crash');
}
else {
$('#GhCsStatus_GH').buttonMarkup({ icon: 'myapp-gh' });
alert('running');
}
}, "json"), 2000);
}
我格式化此代码的方式或我放置函数的位置是否会影响输出?
最佳答案
语法错误,添加更多函数并正确关闭它们:
$(document).ready(function() { // needs anonymous function
GrabGhCsStatus();
});
function GrabGhCsStatus() {
var url = '@Html.Raw(Url.Action("index","GhCs"))';
$.get(url, function (data) {
if (data.GhStatus === 0 || data.CsStatus === 0) {
$('#GhCsStatus_CS').buttonMarkup({
icon: 'myapp-cs'
});
}else{
$('#GhCsStatus_GH').buttonMarkup({
icon: 'myapp-gh'
});
}
setTimeout(GrabGhCsStatus, 2000);
}, "json");
}
关于javascript - 函数运行一次成功然后连续失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774589/