我有以下代码访问变量的JavaScript/jQuery的
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
如何#second中访问myVar的?
我有以下代码访问变量的JavaScript/jQuery的
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
如何#second中访问myVar的?
这取决于你的代码的大背景。你可以这样做:
(function() {
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
})();
创建一个匿名函数并立即调用它。匿名函数的目的是为myVar
提供一个容器,而不需要使得myVar
成为一个全局变量。通常最好避免使用全局变量(尤其是因为它们成为window
对象的属性,它已经有各种各样的垃圾)。具体而言,您分配给您的click
和blur
事件的功能将变为关闭对呼叫内部数据的匿名功能的。他们有权访问myVar
,但没有别的。 More here。
如果您的代码已经在包含范围内,或者您不关心添加到全局名称空间,则不需要匿名函数。
在外部范围定义myVar的:
var myVar;
$('#first').click(function() {
myVar = $(this).next().val();
});
$('#second').blur(function() {
console.log(myVar);
});
T.J. Crowder的答案是你想要的。这只是一个替代方案(使用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'));
});
这里的答案很好。但我认为你正处于从Crockford's JS slideshow中受益的地步。这很好,解释了几个与你的问题有关的问题。
+1为关闭 – 2010-12-17 13:01:13
+1。正确答案。我不知道为什么每个人都在做'(function(){})()'而不是'(function(){}())''。后者似乎更加自然。外括号也不是必需的,但它们表明了某种特定的情况。 – jwueller 2010-12-17 13:05:54
@elusive:为什么不在这里问一个问题,为什么;-) – 2010-12-17 13:09:39