Reputation: 16236
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?
Upvotes: 3
Views: 129
Reputation: 38147
The key is in the explanation on the link you posted :
The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope
This is basically saying that the param1
and param2
variables are defined previously (outer scope) :
$("button").click(function () {
var param1 = "something";
var param2 = "something else";
$.get('myhtmlpage.html', function(){
myCallBack(param1, param2); // this uses the previously declared variables
});
});
Within JavaScript when you call a function myfunc("some text")
for example the actual function could be defined as function myfunc(var1) {
or function myfunc() {
the first example just formally declares a variable name for the first argument ...
function myfunc() {
alert(arguments[0]);
}
myfunc("some text");
arguments that are not formally declared ar available using the arguments
array ... see this doc on MDN
Upvotes: 7
Reputation: 324620
You need to have already defined the variables in order to use them inside a closure like that. Since the get
function puts the result into the first parameter of the anonymous function, you need to put result
there to catch it, if you want to do anything with it.
Try this: Remove the result
parameter again, and add result="Hello World";
at the start of your code.
Upvotes: 1