变量不传递给其他函数

Variable not passing to other functions

本文关键字:其他 函数 变量      更新时间:2023-09-26

我有一张桌子。 当用户单击表单元格时,jquery 会获取单元格内的子项(输入标记)的 id 属性和名称属性。 当我提醒各个变量时,它们会正确发出警报。 但是,当我将值返回到数组并提醒它们我在脚本中遇到问题的其他位置时。例如,当我提醒另一个函数中的值时,我得到[对象HTMLTableCellElement]。

我已经在 document.ready 之后在脚本顶部的任何函数之外声明了 id 和 name 变量。 为什么无法将 id 和名称的正确值获取到另一个匿名函数或函数中。

<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];
});
values2 = $('table tr td').click(function() {

当你把一个函数传递给click时,你说的是"点击这个函数时,调用这个函数"。

然后,调用函数继续。

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

如果要使用这些值来响应单击,则需要在传递给单击的函数(或它调用的函数)中执行此操作。

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