为什么在外部函数中看不到jQuery缓存变量?

时间:2013-07-19 14:17:08

标签: jquery

我很好奇为什么这段代码不起作用。

我无法在$note函数

中看到hey()变量
function hey(kc) {
$note.html(kc);
 }

$(function () {

 var $note = $('#note');    
 hey("Joice");

 });

玩弄小提琴 http://jsfiddle.net/VcdxB/

5 个答案:

答案 0 :(得分:2)

在函数内部使用var关键字时,声明一个只在函数范围内可见的局部变量(函数本身和其他函数)。

答案 1 :(得分:1)

因为绑定到ready事件的函数 local

请检查:http://jsfiddle.net/VcdxB/1/

function hey(kc) {
    $note.html(kc);
}

// now it will be visible in both functions
var $note = $('#note');

$(function () {
    hey("habi");
});

答案 2 :(得分:1)

$ note变量的范围仅限于document.ready()函数。您需要将其移到$(function () etc...之外才能使其正确定位。然后你可以在那个函数中分配它。

var $note;    

$(function () {
    $note =  $('#note');
    hey("habi");
});

答案 3 :(得分:1)

您需要将变量范围设为全局,请使用:

var $note;

function hey(kc) {
    $note.html(kc);
}

$(function () {
     $note = $('#note');    
     hey("habi");
});

答案 4 :(得分:1)

正如其他人所说,这是scope的问题。这是我缓存jQuery对象的模式:

// global scope
// single hash to hold all reference to cached jQuery objects
var $jq = {};

$(function() {

   $jq.note = $('#note'); 
   $jq.name = $('#name'); 

});

function hey(kc) {
    $jq.note.html(kc);
}