2013-10-07 52 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()的返回值不是運行您傳遞的單擊的函數的結果。

如果您想使用這些值來響應點擊,那麼您需要在內部通過點擊(或其調用的函數)來傳遞函數。

如果您想將它們存儲爲稍後使用的全局文件,那麼您需要將它們分配給全局函數,該函數在傳遞給您的函數中單擊而不是作爲返回值。