简体   繁体   中英

Function inside of (document).ready

I am working with a VB.NET site that uses a master page. I have my custom.js file being called in the master page. I had inserted a simple bit of code to test the custom.js:

$(document).ready(function(){
    function sayHello(){
        alert("Hello!");
    }
});

EDIT: Here is how the call is made in my HTML:

<a href="javascript:sayHello();">Something</a>

When I call this function in my .aspx page nothing happens. However, leaving the code in the .aspx alone and moving the function outside of the document.ready enables the code to run. Ideas why this is happening?

EDIT: I have added a related question here

That is because you might be trying to invoke the function sayHello from a global scope where it is defined in the closure of document.ready callback. So it is only accessible inside that. When you move outside of it you are defining it in global scope and it is accessible when you try to access it in the global scope or any other inner scopes.

When I call this function in my .aspx page nothing happens.

You must be getting an error.

You can safely define your function outside the document.ready. You need only to place (most cases) the piece of code that accesses the dom inside the ready handler (unless that script comes after the element in the html).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM