How do I write a jQuery function so that it returns a value that I can access outside the function? I did something like this but when I tried to access it outside the function, it says "undefined":
$(document).ready(function(){
function add(y, z) {
$('p').click(function() {
x = y + z;
开发者_如何转开发 console.log(x); // shows 3
return x;
});
}
var sum = add(1, 2);
console.log(sum); // shows "undefined"
});
This should work. Not sure why you added the click
event there
$(document).ready(function(){
function add(y, z) {
x = y + z;
console.log(x); // shows 3
return x;
}
var sum = add(1, 2);
console.log(sum);
});
function add(y, z) {
$('p').click(function() {
x = y + z;
console.log(x); // shows 3
return x;
});
return y + z;
}
Simple answer - you can't.
The method registered by .click()
is called asynchronously as part of the Javascript event loop.
Your add
function has no return value at all.
If instead what you're trying to do is to create a jQuery style utility function, rather than a method that acts on elements, you would do this:
(function($) {
$.add = function(y, z) {
return y + z;
}
})(jQuery);
usage:
var x = $.add(1, 2);
The function, in that case, is an anonymous callback function that is called when the click event occurs. The way you set it up, what function add(x, y)
does is create a new handler for click events on
tags.
I don't know why click event is added to the function. It should be handled separately. The code should look like this which makes sense according to me.
$(document).ready(function() {
function add(y, z) {
var x = y + z; // good to make it local scope
console.log(x); // shows 3
return x;
}
var sum = add(1, 2);
document.write(sum); // shows "undefined"
});
精彩评论