Could anyone tell me why ‘function()’ right after .ready is needed to make the script work?
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
function() { }defines an inline function, which is then passed as a parameter toready().If you did
or something similar, the return value of
clickwould be passed to the ready function, which would be something completely different. Of course, the same can be done with named functions:Note the lack of
()afterinitializeon the last line, which means “pass this function” instead of “call this function and pass the return value”. By the way, just passing a function to$itself ($(function() { ... });) is a shortcut form for$(document).ready.