我有一张 table 。当用户单击表格单元格时,jquery 会获取单元格内部子项(输入标签)的 id 属性和 name 属性。当我警告各个变量时,它们会正确警告。但是,当我将值返回到数组并警告它们在脚本中遇到问题的其他位置时。例如,当我警告另一个函数中的值时,我得到 [object HTMLTableCellElement]。
我已经在 document.ready 之后的脚本顶部的任何函数之外声明了 id 和 name 变量。为什么无法将正确的 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>
最佳答案
而不是
values2 = $('table tr td').click(function(){
return [id , name];
});
使用
$('table tr td').click(function(){
values2 = [id , name];
});
关于javascript - 变量未传递给其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19228760/