开发者

Calling functions from previously-loaded JS file

I'm using jQuery. I have a JS file (super.js) containing:

$("#content").load("/profile");

function setHash(hash) {
   location.hash = "#/:-)/"+hash;
}

"/profile" loads another external JS file (profile.js) containing a call to setHash:

setHash('blabber');

But it doesn't seem to work (setHash is undefined).

Edit: setHash is called from within a function in profile.js:

function changePage(type) {
    setHash('bla/'+type);
}

How can I get "global" functions to work in JS files included in dynamically-loaded pages?

Than开发者_C百科ks, Albert


Move the setHash function outside of the $(document).ready(function(){}). This will make it a global function that can be called anywhere. If it is inside a function(){} closure it can only be called from within that closure. If you and up moving many functions outside the closure, I would recommend namespacing them:

var myApp = {};
myApp.setHash = function() { 
                  // your code 
                };

myApp.setHash(); // invocation
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜