JavaScript函数的问题addElement()和insertAt()

时间:2017-09-01 20:19:46

标签: javascript dom html-table

在David Flanagan的书" JavaScript:The Definitive Guide" (O' Reilly),我看到函数addElement()和insertAt()作为创建和精确放置新DOM元素的方法。

作为测试它们的一种方法,我决定编写一个脚本来计算比例对数表。我遇到的问题是,当我尝试从调用脚本的最小HTML shell运行脚本时,我几乎什么都没有。表格(24 x 60)并未真正显示或填充。这是我的剧本:

// Initialize variables to be used in control structures
var hr;
var min;
var x;
var y;
var b;

// Create multidimensional arrays for logarithms and their bases
var logBases = new Array(24);
for (hr = 0; hr < logBases.length; hr += 1) {
    logBases[hr] = new Array(60);
}

var logarithms = new Array(24);
for (hr = 0; hr < logarithms.length; hr += 1) {
    logarithms[hr] = new Array(60);
}

//Initialize logarithm bases to starting point of table
logBases[0][0] = 1440;

for (x = 0; x < 24; x += 1) { //Rows
    for (y = 0; y < 60; y += 1) { //Columns
        if (x === 0 && y === 0) { // If very first iteration
            continue; // Then continue to next iteration
        } else if (x > 0 && y === 0) { // Otherwise, if starting new column,
            b = logBases[x - 1][59]; // Reference last log base of previous column
        } else { // If neither case is true,
            b = logBases[x][y - 1]; // Reference previous log base in current column
        }
        logBases[x][y] = b * ((x * y) / (x * (y - 1)));
        logarithms[x][y] = Math.log(logBases[x][y]);
    }
}

//Grab main table element with "tpl" id
var tpl = document.getElementById("tpl");

////////////////////////////
// Build hour row headers //
////////////////////////////
var tplNumHeads = addElement('tr', 'tplNumheads'); // Create numeric header row
tpl.appendChild(tplNumHeads); // Append header row as last child of table

for (hr = 0; hr < 24; hr += 1) { // Each iteration creates one row.
    var idVal = 'tplHr' + hr;
    var hourHead = addElement('th', idVal, hr);
    insertAt(tplNumHeads, hourHead);
}

//////////////////////////////////////////////////////////////////
// Create table cells and populate with appropriate logarithms. //
//////////////////////////////////////////////////////////////////
for (min = 0; min < 60; min += 1) {
    // ---Create new row object ---
    var rowID = 'tplMin' + min;
    var row = addElement('tr', rowID);

    // ---Create and insert <th> element---
    var headID = 'tplMinHead' + min;
    var rowHead = addElement('th', headID, min);
    insertAt(row, rowHead);

    // ---Build data cells---
    for (hr = 0; hr < 24; hr += 1) {
        var cellID = 'tpl' + hr + '_' + min;
        var cellHeader = 'tplHr' + hr;
        var cellContent = logarithms[hr][min].toFixed(4); // Logarithms to four decimal places.
        var cell = addElement('td', cellID, cellContent, 'headers', cellHeader);
        insertAt(row, cell);
    }
insertAt(tpl, row);
}

0 个答案:

没有答案