javascript意外标识符

javascript unexpected identifier

本文关键字:标识符 意外 javascript      更新时间:2023-09-26

我正在尝试压缩我的JavaScript代码,以减少网站上的流量。它一直运行良好,但现在我遇到了一个无法解决的错误。

我把ajax函数变成了一行:

function(){if(xmlhttp.readyState==4&&xmlhttp.status==200){document.getElementById("content").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();}

但是chrome控制台告诉我这行有一个意外的标识符。Firefox说这一行少了一个分号。

我一直在努力找出问题所在,但我找不到错误,有人能帮我吗?

是的,您的}太多了。无论如何,压缩自己往往会导致错误。

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

请改用闭包编译器。

我建议使用http://jsbeautifier.org/-如果您将代码片段粘贴到其中并按美化,则会立即看到错误。

在这种情况下,最好重新添加空白,这会使语法错误立即显现出来:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

太多了。此外,在函数的关闭}之后,您应该添加一个;在xmlhttp.open()之前

最后,我看不出上面的匿名函数有什么作用。它从未被执行或引用。你确定你粘贴了正确的代码吗?

responseText;}}的末尾或从行的末尾移除一个}

代码中似乎有一个额外的花括号。

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

如果你想压缩JS,我建议你使用Closure Compiler,这是谷歌为网站开发人员提供的工具。它还提供了可以由您自己实现的附加API