0

I register a function to a button with onclick attribute, and define this function in $() block(I know it is a bad practice, and it is just an example), when I click the button, an error occurs: Uncaught ReferenceError: hello is not defined. Here is my code:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function(){
 function hello(){
 alert('hello');
 }
});
</script>
</head>
<body>
<input type="button" id="btn" value="click" onclick="hello()"/>
</body>

if I put hello function code out of $() block, it works. I know $() is executed when DOM is parsed, when I click the button, the DOM must already has been parsed, so why it reports an error? Thanks.

asked Mar 18, 2013 at 13:29
1
  • your function named hello is scoped to the anonymous function you pass to $() so it can't be called from your onclick handler. Commented Mar 18, 2013 at 13:30

2 Answers 2

2

your code assumes hello is a global function which it is not.

$(function(){
 function hello(){
 alert('hello');
 }
 $("#btn").click(hello);
});
answered Mar 18, 2013 at 13:30
Sign up to request clarification or add additional context in comments.

1 Comment

window.hello = function(){ will make it global. anyway inline js sucks
1

There is no difference, except that functions executed (not defined) inside a $.ready block are guaranteed to execute after the DOM is ready to be accessed/manipulated.

Your issue is one of scoping; you've created a local function which isn't accessable at the global scope where your event is being handled.

answered Mar 18, 2013 at 13:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.