0

为什么这段 JavaScript 代码会产生这个有趣的结果?查看 RowID 和 CellID。

Result: 
[R0C0]: Apple   [R1C1]: 400
[R2C0]: Google  [R3C1]: 700


    <html>
     <head>
      <script src="ClosureAccessStaticVariable.js" type="text/javascript"></script>
      <script src="jquery-1.9.1.js" type="text/javascript"></script>
     </head>
     <body>
      <div id="panelTable"></div>
      <script>
        function Table(dataRows){
        var rows = [];
        this.GetTable = function(){
            var table = $("<table>");
            $(rows).each(function(){
                table.append(this.GetRow());
            });
            return table;
        }
        function init(){
            $(dataRows).each(function(index){
                rows[index] = new TableRow(this);
            });
        }
        function TableRow(rowData){
            var cells = [];
            this.GetRow = function(){
                var row = $("<tr>");
                $(cells).each(function(){
                    row.append(this.GetCell());
                });
                return row;
            }
            function init(){
                var i=0;
                for(var cellName in rowData){
                    cells[i] = new TableCell(rowData[cellName]);
                    i++;
                }
            }
            function TableCell(text){
                this.GetCell = function(){
                    if(TableRow.ID == undefined)
                        TableRow.ID = 0;
                    if(TableCell.ID == undefined)
                        TableCell.ID = 0;

                    var rowId = TableRow.ID;
                    var cellId = TableCell.ID;
                    TableRow.ID = TableRow.ID + 1;
                    TableCell.ID = TableCell.ID + 1;
                    return $("<td style='border:1px solid lightgray;padding:2px;'>").html("[R"+rowId+"C"+cellId+"]: "+text);
                }
            }
            init();
        }
        init();
        }
        var data = [ { Name: "Apple", Value: 400}, {Name: "Google", Value: 700}];
        var table = new Table(data);
        var tableDom = table.GetTable();
        $("#panelTable").append(tableDom);
    </script>
     </body>
    </html>
4

1 回答 1

0

您正在增加每个单元格中的行:

this.GetCell = function(){
    var rowId = TableRow.ID;
    var cellId = TableCell.ID;
    // The row ID gets updated 
    TableRow.ID = TableRow.ID + 1;
    TableCell.ID = TableCell.ID + 1;
于 2013-05-02T20:17:18.077 回答