2012-01-30 70 views
0

我想嘗試一個lib ala jquery,但我不明白爲什麼我的方法getUrl不輸出任何內容,是嗎?javascript匿名函數:爲什麼我的腳本不工作

mylib.js

(function() { 

    var scripts = document.getElementsByTagName('script'); 
    var index = scripts.length - 1; 
    var thisScript = scripts[index]; 

    var myLib = {  
     getUrl: function() { 
      return thisScript; 
     }    
    } 
} 

if (!window.$$) {window.$$ = myLib} 

)(); 

和mytest.html

<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.js"></script> 
    <script src="mylib.js" type=text/javascript></script> 
</head> 

<body> 
    <DIV id=url>url</DIV> 
    <script> 
    var url = $$.getUrl(); 
    jQuery("#url").html(url); 
    </script> 
</body> 
</html> 

回答

5

您的代碼有一個錯位的}

(function() { 
    var scripts = document.getElementsByTagName('script'); 
    var index = scripts.length - 1; 
    var thisScript = scripts[index]; 

    var myLib = {  
     getUrl: function() { 
      return thisScript; 
     }    
    }; 
//} <-- Remove this. 

    if (!window.$$) {window.$$ = myLib;} 
} // <-- Add this, the closing brace of the anonymous function 
)(); 
+0

感謝我找JS很難找到錯誤:) – user310291 2012-01-30 20:08:37

相關問題