变量不传递给其他函数

时间:2013-10-07 15:29:40

标签: javascript jquery

我有一张桌子。当用户单击表格单元格时,jquery会抓取单元格内的id属性和子属性的名称属性(输入标记)。当我提醒各个变量时,他们会正确提醒。但是,当我将值返回到数组并提醒其他人在我运行的脚本中的问题。例如,当我提醒另一个函数中的值时,我得到[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>

2 个答案:

答案 0 :(得分:3)

而不是

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

使用

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

答案 1 :(得分:0)

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

当您将函数传递给click时,您会说“单击此项时,请调用此函数”。

然后呼叫功能继续。

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

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

如果您想将它们存储为全局以供日后使用,则需要将它们分配给您传递的函数内的全局以单击,而不是作为返回值。

相关问题