我很好奇为什么这段代码不起作用。
我无法在$note
函数
hey()
变量
function hey(kc) {
$note.html(kc);
}
$(function () {
var $note = $('#note');
hey("Joice");
});
答案 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);
}