2012-07-15 22 views
0

我有這樣的代碼工作正常:的Javascript意想不到的標識,而bookmarkleting

if (typeof jQuery === "undefined" || jQuery.fn.jquery !== '1.4.2') { 
var script_tag = document.createElement('script'); 
script_tag.setAttribute("type","text/javascript"); 
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); 
script_tag.onload = main; // Run main() once jQuery has loaded 
script_tag.onreadystatechange = function() { // Same thing but for IE 
if (this.readyState == 'complete' || this.readyState == 'loaded') main(); 
} 
document.getElementsByTagName("head")[0].appendChild(script_tag); 
} else { 
    main(); 
} 

但是當我嘗試壓縮它通過bookmarkleter我有「意外的標識符」錯誤

javascript:(function(){if(typeof%20jQuery===%22undefined%22%20||%20jQuery.fn.jquery%20!=='1.4.2'){var%20script_tag=document.createElement('script');script_tag.setAttribute(%22type%22,%22text/javascript%22);script_tag.setAttribute(%22src%22,%22http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js%22);script_tag.onload=main;script_tag.onreadystatechange=function(){if(this.readyState=='complete'%20||%20this.readyState=='loaded')main();}document.getElementsByTagName(%22head%22)[0].appendChild(script_tag);}else{main();}})(); 

建議嗎?

感謝

+0

...你爲什麼使用jQuery 1.4.2? – 2012-07-15 19:22:22

+0

我不是沒有使用,只是測試我發現的代碼 – lorussian 2012-07-15 19:23:06

+0

啊,好的。我會說......-) – 2012-07-15 19:23:43

回答

3

不知道這是bookmarkleter或不是一個錯誤,但是你document.getElementsByTagName("head")[0].appendChild(script_tag);之前需要一個分號,如果它要全部擠進這樣的一條線。

一旦你這樣做,意外的標識符錯誤消失。除非事先已經定義了main,否則將會出現一個新的「main is not defined」錯誤。

+0

+1。事實證明,已經有很多關於縮寫詞沒有正確處理隱式分號的討論。例如,請參閱http://news.ycombinator.com/item?id=1547647。另請參閱github上的這個令人敬畏的討論:https://github.com/twitter/bootstrap/issues/3057「Zzzzzing」 – 2012-07-15 19:57:11