简体   繁体   中英

javascript anonymous function : why my script doesn't work

I want to try to a lib ala jquery but I don't understand why my method getUrl doesn't output anything, do you ?

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}

)();

and in 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>

Your code had a misplaced } .

(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
)();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM