2010-12-17 44 views
0

我有以下代码访问变量的JavaScript/jQuery的

$('#first').click(function() { 
    myVar = $(this).next().val(); 
}); 

$('#second').blur(function() { 
    console.log(myVar); 
}); 

如何#second中访问myVar的?

回答

5

这取决于你的代码的大背景。你可以这样做:

(function() { 
    var myVar; 

    $('#first').click(function() { 
     myVar = $(this).next().val(); 
    }); 

    $('#second').blur(function() { 
     console.log(myVar); 
    }); 
})(); 

创建一个匿名函数并立即调用它。匿名函数的目的是为myVar提供一个容器,而不需要使得myVar成为一个全局变量。通常最好避免使用全局变量(尤其是因为它们成为window对象的属性,它已经有各种各样的垃圾)。具体而言,您分配给您的clickblur事件的功能将变为关闭对呼叫内部数据的匿名功能的。他们有权访问myVar,但没有别的。 More here

如果您的代码已经在包含范围内,或者您不关心添加到全局名称空间,则不需要匿名函数。

+2

+1为关闭 – 2010-12-17 13:01:13

+0

+1。正确答案。我不知道为什么每个人都在做'(function(){})()'而不是'(function(){}())''。后者似乎更加自然。外括号也不是必需的,但它们表明了某种特定的情况。 – jwueller 2010-12-17 13:05:54

+0

@elusive:为什么不在这里问一个问题,为什么;-) – 2010-12-17 13:09:39

2

在外部范围定义myVar的:

var myVar; 

$('#first').click(function() { 
    myVar = $(this).next().val(); 
}); 

$('#second').blur(function() { 
    console.log(myVar); 
}); 
0

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')); 
}); 
0

这里的答案很好。但我认为你正处于从Crockford's JS slideshow中受益的地步。这很好,解释了几个与你的问题有关的问题。