【发布时间】:2025-11-24 18:55:02
【问题描述】:
我有一个 javascript 函数,在大多数情况下,它需要对我传递给它的 jQuery 对象做一些事情。有一个例外,该函数不需要 jQuery 对象,但是因为我已经编写它来接受字符串(命令)和 jQuery 对象,所以当我调用它时我需要一些东西来传递它。我的功能如下:
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),但没有成功。有什么想法吗?
谢谢。
更新
正如许多人回答的那样,事实证明我并没有测试 $item 是否为空,所以它每次都试图设置一些东西(无论是否传递了一个对象)。我将我的功能代码更改为:
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);
似乎工作正常。作为对我最初问题的回答,“null”似乎足以作为空白或虚拟对象,或者根本不需要传递,在这种情况下,函数会自动为其分配一个空值。感谢您的回复。
【问题讨论】:
-
if($item)有什么问题?不能改代码什么的?
标签: javascript jquery object parameters