我有一張表。當用戶點擊一個表格單元格時,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>
請在提交您的問題之前正確縮進。 –
另外,當涉及到代碼塊這個大時,jsfiddles更可取 – Overcode
你的回報什麼都不做。它不在函數內部(從技術上說,它處於Document ready函數中,但這不是您嘗試使用返回函數的「函數」)。此外,您將'values'變量設置爲等於函數,而不是函數的返回值。 –