我有一个javascript函数,在大多数情况下,需要使用传递它的jQuery对象进行操作。有一个例外,函数不需要jQuery对象,但是因为我已经写了它来接受一个字符串(命令)和一个jQuery对象,所以在我调用它时需要通过它。我的函数如下所示:如何将哑元jQuery对象传递给Javascript函数
function handleNotes(command, $item) {
var $textArea = $('#textarea_' + currentDialog); // currentDialog = global var
var $notesDiv = $('#' + $item.attr('id') + "_notes");
switch (command) {
case "show":
// do something with $notesDiv and $textArea
break;
case "hide":
// do something with $notesDiv and $textArea
});
break;
case "hide only":
// do something with $textArea only
}
}
我的函数调用,我的问题是:
handleNotes("hide only");
我试过handleNotes("hide only", null)
,我已经试过handleNotes("hide only", Object)
没有运气。有任何想法吗?
谢谢。
UPDATE
所以尽可能多的人回答说,事实证明我没有测试为$项目为空,所以它试图每次设置的东西(一个对象是否被传递给它或不)。我改变了我的功能代码这样:
function handleNotes(command, $item) {
var $textArea = $('#textarea_' + currentDialog); // currentDialog = global var
if($item) { // if not null
var $notesDiv = $('#' + $item.attr('id') + "_notes");
}
switch (command) {
case "show":
// do something with $notesDiv and $textArea
break;
case "hide":
// do something with $notesDiv and $textArea
});
break;
case "hide only":
// do something with $textArea only
}
}
而我的函数调用:handleNotes("hide only", null);
看起来工作得很好。作为我原来的问题的答案,看起来“空白”就足以作为空白对象或虚拟对象,或者根本不需要传递,在这种情况下,函数会自动为它指定一个空值。感谢您的回应。
'if($ item)'有什么问题?你不能改变代码或什么? – 2009-11-24 02:25:20