我有以下代码
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});如何在#秒内访问myVar?
发布于 2010-12-17 21:00:18
这取决于代码的更广泛的上下文。您可以这样做:
(function() {
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
})();这会创建一个匿名函数并立即调用它。匿名函数的目的是在不使myVar成为全局变量的情况下为myVar提供容器。通常最好避免使用全局变量(尤其是因为它们变成了window对象的属性,这个对象已经有各种各样的垃圾了)。具体地说,分配给click和blur事件的函数将成为匿名函数调用内部数据的闭包。他们可以访问myVar,但其他用户无法访问。More here。
如果您的代码已经在一个包含作用域中,或者您不关心添加到全局名称空间,则不需要匿名函数。
发布于 2010-12-17 21:00:03
在外部作用域中定义myVar:
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});发布于 2010-12-17 21:04:21
T.J.克劳德的回答满足了你的要求。这只是一种替代方法(使用jQuery data storage方法):
$('#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'));
});https://stackoverflow.com/questions/4470656
复制相似问题