hiway
hiway

Reputation: 3976

what is the difference between a function defined inside jquery ready block and one outside

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.

Upvotes: 0

Views: 287

Answers (2)

ek_ny
ek_ny

Reputation: 10243

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

$(function(){
    function hello(){
        alert('hello');
    }
    $("#btn").click(hello);
});

Upvotes: 2

user229044
user229044

Reputation: 239260

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.

Upvotes: 1

Related Questions