Access variables javascript/jquery
I have the following code
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
How to access myVar within #开发者_如何学编程second ?
It depends on the wider context of your code. You can do this:
(function() {
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
})();
That creates an anonymous function and calls it right away. The purpose of the anonymous function is to provide a container for myVar
without making myVar
a global variable. Global variables are generally best avoided (not least because they become properties of the window
object, which already has all sorts of junk stuck on it). Specifically, the functions you're assigning to your click
and blur
events become closures over the data inside the call to the anonymous function. They have access to myVar
, but nothing else does. More here.
If your code is already inside a containing scope, or you don't care about adding to the global namespace, you don't need the anonymous function.
Define myVar in the outer scope:
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
T.J. Crowder's answer does what you want. This is just an alternative (using the jQuery data storage methods):
$('#first').click(function() {
// Assign this element to have data with the key 'myVar'
$(this).data('myVar', $(this).next().val());
});
$('#second').blur(function() {
// Read the data from the other element
console.log($('#first').data('myVar'));
});
The answers here are good. But I think you're at the point where you'd benefit from reading Crockford's JS slideshow. It's very good and explains several matters related to your question.
精彩评论