javascript - 变量未传递给其他函数

标签 javascript jquery

我有一张 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/

相关文章:

javascript - 将变量添加到动画CSS

javascript - 在 'document_start' 处运行的内容脚本会阻止网页上的 JS 脚本?

jquery - 如何在JQuery中使用$.each循环遍历json代码

javascript - 按多维 id 数组求和

javascript - 简单的 jQuery 验证失败

javascript - 透视投影什么也没显示

javascript - 有没有一种简单的方法可以像 charCodeAt 从文本转换为 ASCII 一样从二进制转换为 ASCII?

javascript - 一个 JavaScript 对象可以有一个原型(prototype)链,同时也是一个函数吗?

jquery - Flot Graph 每日访客量

javascript - 单击后折叠菜单打开并处于事件状态