开发者

Jquery: Calling functions from different documents

I've got some Jquery functions that I keep in a "custom.js" file. On some pages, I need to pass PHP variables to the Jquery so some Jquery bits need to remain in the HTML documents. However, as I'm now trying to refactor things to the minimum, I'm tripping over the following:

If I put this in my custom.js:

$(document).ready(function()
{
   function s开发者_JS百科ayHello() {
      alert("hello");
   }
}

And this in a HTML document:

<script type="text/javascript">
   $(document).ready(function()
   {
      sayHello();
   });
</script>

... the function doesn't get called. However, if both are placed in the HTML document, the function works fine.

Is there some kind of public property I need to declare for the function or how do I get Jquery functions in my HTML to talk to external .js files? They're correctly included and work fine otherwise.

Thanks.


The problem is you're defining sayHello within the anonymous function that is declared on this line:

$(document).ready(function()

As a result, sayHello is scoped to only that function. If you wish to call sayHello from anywhere else in your application, such as the HTML on your page or another line in custom.js, you will need to change custom.js and define it outside the call to $(document).ready:

function sayHello()
{
   alert("hello");
}

$(document).ready(function()
{
   sayHello();
}


just make the function a global variable

sayHello=function() {
    alert("hello");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜