So, near the bottom the jQuery basic pages, it gives this example, NOTICE how the anonymous function() does not have params. Quote JQuery page says
The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.
$.get('myhtmlpage.html', function(){
myCallBack(param1, param2);
});
So, I gave it a try based on this example
My code is like this, similar thing, at line 10, I have an anonymous function(result), but I need to add the param “result” can’t be just function() as suggested by JQuery website, or it won’t work:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var GetResults = function (result) {
$("div").html(result);
}
$("button").click(function () {
$.get("demo_ajax_load.txt", function (result) {
GetResults(result);
});
});
});
</script>
</head>
<body>
<div>
<h2>Let AJAX change this text</h2>
</div>
<button>Change Content</button>
</body>
</html>
My question is, why does JQuery page says it will work with just function() without params? I have to add function(result) to make it work? Am I missing something?
The key is in the explanation on the link you posted :
This is basically saying that the
param1andparam2variables are defined previously (outer scope) :Within JavaScript when you call a function
myfunc("some text")for example the actual function could be defined asfunction myfunc(var1) {orfunction myfunc() {the first example just formally declares a variable name for the first argument …arguments that are not formally declared ar available using the
argumentsarray … see this doc on MDN