2009-11-24 85 views
0

我有一个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);

看起来工作得很好。作为我原来的问题的答案,看起来“空白”就足以作为空白对象或虚拟对象,或者根本不需要传递,在这种情况下,函数会自动为它指定一个空值。感谢您的回应。

+0

'if($ item)'有什么问题?你不能改变代码或什么? – 2009-11-24 02:25:20

回答

1

可避免测试误差,看是否$item试图访问它之前设置的attr方法,像这样:

function handleNotes(command, $item) { 

if ($item) { 
... 

    var $textArea = $('#textarea_' + currentDialog); // currentDialog = global var 
    var $notesDiv = $('#' + $item.attr('id') + "_notes"); 

    etc.. 

然后,如果你调用使用handleNotes("hide only", null)方法你会避免执行代码要执行对您的jQuery对象..

+0

你甚至可以调用省略参数的函数:'handleNotes(“hide only”);'和'$ item'参数将是'undefined',它将在if语句中计算为'false'。 – CMS 2009-11-24 04:26:05

1

在JavaScript它的罚款打电话用更少的参数的函数,那么它声明 - 但你有一个错误,因为你在函数代码总是尝试访问$item

如果您重写该函数,以便在需要使用它时只访问$item,则应该能够避免这些错误。

function handleNotes(command, $item) { 

    var $textArea = $('#textarea_' + currentDialog); // currentDialog = global var 
    var $notesDiv; 
    if (command == "show" || command == "hide") { 
     $notesDiv = $('#' + $item.attr('id') + "_notes"); 
    } 

    switch (command) { 
    // ... 
    } 
} 
1

它可能是因为您使用$ item,而不知道它是否可以使用。尝试:

var $notesDiv = $item ? $('#' + $item.attr('id') + "_notes") : null; 
1

它看起来像你有问题,因为你尝试汤姆访问attr项目时,它不通过。在访问它之前,您应该确保该成员存在。

即。

if(item && item.attr) 
1

你也可以构造一个空的jQuery设置像这样:

jQuery([]) 

这会给你一套零个元素,就像你说jQuery("#asdfkadskfkdfas")。所有jQuery方法都可以在不抛出异常的情况下工作,尽管大多数方法都会返回合法值undefined。所以,你的例子是:

handleNotes("hide only", jQuery([])); 

但是,更好的解决办法,就是要调整你的功能,如接受的答案建议。