开发者

Calling functions from previously-loaded JS file

开发者 https://www.devze.com 2023-02-21 01:28 出处:网络
I\'m using jQuery. I have a JS file (super.js) containing: $(\"#content\").load(\"/profile\"); function setHash(hash) {

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

精彩评论

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