2013-10-07 50 views
0

我有一张表。当用户点击一个表格单元格时,jquery获取单元格内部的id属性和子元素的名称属性(输入标签)。当我提醒各个变量时,他们会正确提醒。但是,当我将这些值返回给一个数组并在脚本中的其他位置提醒他们其他问题时。例如,当我警告另一个函数中的值时,我得到[对象HTMLTableCellElement]。变量不传递给其他函数

我已经在document.ready之后的脚本顶部的任何函数之外声明了id和名称变量。为什么无法将id和name的正确值输入到另一个匿名函数或函数中。

<script> 
    $(document).ready(function() { 
     var id = 0; 
     var name = 0; 
     var values2 = []; 

     //when a table cell is clicked 
     values2 = $('table tr td').click(function() { 

      //grab the id attribute of the table cell's child input tags that have a class of hidden 
      id = $(this).children("input[class='hidden']").attr("id"); 
      alert(id); //<----- alerts id properly (output for example is 25) 

      //grab the name attribute of the table cell's child input tags that have a class of hidden 
      name = $(this).children("input[class='hidden']").attr("name"); 
      alert(name); //<----- alerts id properly (output for example is firstinput) 

      return [id , name]; //<------ here is where I try to return both these values in to an array 
           // so that I can use the values else where in the script. However 
           // I am not able to use the values 
     }); 

     $("#nameForm").submit(function(event) { 
      // Stop form from submitting normally 
      event.preventDefault(); 
      alert(values2[0]); // <----alerts [objectHTMLtableCellElement] 
           //this should alert ID 

      var posting = $.post("comments.php", $('#nameForm').serialize(), function(data) { 
       $('#result').html(data); 
      }); 

      return false; 
      // $('#result').html(term); 
     }); 
    }); 
</script> 
+3

请在提交您的问题之前正确缩进。 –

+0

另外,当涉及到代码块这个大时,jsfiddles更可取 – Overcode

+0

你的回报什么都不做。它不在函数内部(从技术上说,它处于Document ready函数中,但这不是您尝试使用返回函数的“函数”)。此外,您将'values'变量设置为等于函数,而不是函数的返回值。 –

回答

3

而不是

values2 = $('table tr td').click(function(){ 
    return [id , name]; 
}); 

使用

$('table tr td').click(function(){ 
    values2 = [id , name]; 
}); 
+0

改变返回到实际变量值将存储在似乎工作..谢谢! –

+0

@FranklinNoel,很高兴我能帮上忙 – Satpal

0
values2 = $('table tr td').click(function() { 

当你传递一个函数来click你说 “当这个被点击时,调用这个函数”。

然后调用函数继续。

click()的返回值不是运行您传递的单击的函数的结果。

如果您想使用这些值来响应点击,那么您需要在内部通过点击(或其调用的函数)来传递函数。

如果您想将它们存储为稍后使用的全局文件,那么您需要将它们分配给全局函数,该函数在传递给您的函数中单击而不是作为返回值。