I have created a function inside a .click
$('#BeforeFunction').click(function(){
//something is entered here then the function below is called
Hello();
});
$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}
});
But the function when called causes an error, the message being Hello is not defined.
What is wrong exactly?
-
Scoping (or rather, your understanding of it) is wrong.user395760– user3957602011年01月22日 18:36:50 +00:00Commented Jan 22, 2011 at 18:36
4 Answers 4
ECMA-/Javascript has a function scope (also called, lexical scope). That means, everything you define within a function is only visible within the scope/context of this function. Hence, Hello is only known within the context of the event-handler function from HitMe.
Probably the best way to create such a function, is NOT to clobber the global namespace (putting it into the window object), but to define your own namespace / scope.
(function($) {
function hello() {
alert ('Hit button is pressed');
}
$('#BeforeFunction').click(function(){
//something is entered here then the function below is called
Hello();
});
$('#HitMe').click(function(){
Hello();
});
}(jQuery));
3 Comments
You have to define function Hello() outside the click scope.
Comments
The curly braces define a scope and limit the definition of Hello function to that scope of "HitMe" function. Define your Hello function outside of the "Hitme" function, preferably before calling it. And you should be fine.
Comments
Each of those click event handlers has its own scope. Anything that you create inside them can't be seen from anywhere else. The reason you're getting that error is that the first click handler doesn't know what Hello is. To get around, that, define your Hello function before your click handlers
function Hello() {
alert ('Hit button is pressed');
}
$('#BeforeFunction').click(function(){
//something is entered here then the function below is called
Hello();
});
$('#HitMe').click(function(){
//something here.....
});
If you want to understand the concept of JavaScript scope any better, there's a pretty good explanation on Digital Web