I'm trying to work with different loaded JavaScript
in my page, but I'm not able to let them talk.
<html>
<script type="text/javascript" src="jquery144.js"></script>
<script type="text/javascript" src="shared_functions开发者_C百科.js"></script>
<script type="text/javascript" src="page_function_callers.js"></script>
</html>
// shared_functions.js
$(document).ready (function () {
function sayHello (what) {
alert (what);
}
});
// page_function_callers.js
$(document).ready (function () {
$("div.my_button").click (function () {
sayHello ("Hello world!");
});
});
I work with jQuery and I'd like to use this way because it should let me recyle many public methods. Where I'm wrong?
The function sayHello
is declared inside the scpoe of the DOMReady
event ( $(document).ready
). It will not be available outside of that scope. But there is no need to declare a function inside that scope. Even if sayHello
uses a lot of DOM objects (which in your example it doesn't), it will not be executed until it's being called, so the only thing you need to make sure is that such a function is not called until after DOMReady.
So you can simply remove the first and the last line in shared_functions.js, i.e. $(document).ready(function() {
and });
respectively, and your code will work.
When you declare "sayHello" (does anybody remember that Charlotte Church song? Gosh, the memories ...) inside the "ready" function, it's local to that function. You can make it global if you like by doing this:
window['sayHello'] = function sayHello(what) {
alert(what);
};
(It's nice to give the function a "local" name — the name after the "function" keyword — because then the function won't show up as "anonymous" in Firebug.)
I would encourage you to investigate making your global function into a jQuery plugin, or at least a jQuery "global" by putting it on the jQuery object instead of "window".
Try defining the function sayHello
outside of your call $(document).ready
.
In your code above, the sayHello() method is only defined inside the anonymous function's scope.
This code might work better for you:
// shared_functions.js
window.MyNamespace = window.MyNamespace || {};
MyNamespace.sayHello = function(what)
{
alert(what);
};
// page_function_callers.js
$(document).ready (function ()
{
$("div.my_button").click (function ()
{
MyNamespace.sayHello('hello world');
});
});
Make sure you're loading your JS files in the right order tho. There are more elegant solutions out there, but this is a fairly simple and straightforward one.
One advantage to this approach would be not polluting the global namespace.
精彩评论