What does $(function() {} ); do?

What does $(function() {} ); do?

Sometimes I make a function and call the function later.

Example:

function example { alert('example'); }
example(); // <-- Then call it later

Somehow, some functions cannot be called. I have to call those functions inside:

$(function() { });

What do $(function() {}); and (function() { }); mean, and what's the difference/purpose of these?

回答1

$(function() { ... });

is just jQuery short-hand for

$(document).ready(function() { ... });

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

$( document ).ready()

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

// A $( document ).ready() block.
$( document ).ready(function() {
    console.log( "ready!" );
});

Experienced developers sometimes use the shorthand $() for $( document ).ready(). If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form.

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
});

You can also pass a named function to $( document ).ready() instead of passing an anonymous function.

// Passing a named function instead of an anonymous function.
 
function readyFn( jQuery ) {
    // Code to run when the document is ready.
}
 
$( document ).ready( readyFn );
// or:
$( window ).on( "load", readyFn );

实例

https://github.com/aspnet/jquery-validation-unobtrusive/blob/master/src/jquery.validate.unobtrusive.js#L428

 $(function () {
        $jQval.unobtrusive.parse(document);
    });
原文地址:https://www.cnblogs.com/chucklu/p/14263298.html