JavaScript/jQuery wierdness

I was editing some code a few days ago, and I added another function within the scope of $(function{}); and I called it within my JavaScript code, and it kept giving me reference errors. After a few minutes I got frustrated and tried to make a simple HTML code call the JavaScript function and nothing. Same error!
I decided to get the new function out of the $(function {} ); area and place it right above it, and wouldn’t you know. It worked.
Does Not Work
When linkClick value is added to the HTML and clicked, I get a reference error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script type="text/javascript"> $(function() { function myFunction() { alert("hello"); } $.ajax({ url : 'http://somewherecool.com/yaay', data: {"Key":Key}, type: 'post', dataType: 'json', success : function(response) { //more code var linkClick = '<a href="#" onclick=" myFunction()">Click</a>'; //doesn't work //more code $('#htmBtn').html(linkClick); } }); }); // ]]></script> |
Works
When I move myFunction out of the $(function() {}); scope it works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script type="text/javascript"> function myFunction() { alert("hello"); } $(function() { $.ajax({ url : 'http://somewherecool.com/yaay', data: {"Key":Key}, type: 'post', dataType: 'json', success : function(response) { //more code var linkClick = '<a href="#" onclick=" myFunction()">Click</a>'; //now it works //more code $('#htmBtn').html(linkClick); } }); }); // ]]></script> |
I kept searching for a reason why this happens. Is it a browser thing? Scope thing? Ajax thing? I couldn’t find an exact answer. What do you think?