jQuery can I use append/appendTo in this javascrip

2019-08-31 10:30发布

问题:

I have created a function that successfully appends a table with rows/cells and populates them from an array. The problem is that they are being appended to the top of the table.

It is doing this because the line var row = tbody.insertRow(r);...I think/hope.

The function to look at in the link below is appendTable(id)

Here is the working example that appends to the top: http://jsfiddle.net/JEAkX/4/

I was thinking something like this would work: var row = insertRow(r).appendTo('tbody>tr:last'); however it just broke the function.

I also tried MANY different combinations of .append() and .appendTo() on that same line with no success. As a last ditch effort I tried variations on the linecell.innerHTML = "<input type='text' size='1' value='" + subset[i++] + "' />" but I believe by that time the location is already decided.

Here is the function extracted from the example:

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 2; r++) {
        var row = tbody.insertRow(r);
        for (var c = 0; c < 4; c++) {
            var cell = row.insertCell(c);
            cell.innerHTML = "<input type='text' size='1' value='" + subset[i++] + "' />"
        }
    }
}

On a side not I tried (unsuccessfully) insertAfter at one point but read that I would not be able to use it on something that didn't exist on page load.

回答1:

insertRow adds a row at the specified index.

When that parameter (r in your code) is zero, it adds the row to the top of the table. To add them to the end instead, use the current length of the table as your starting point:

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var length = tbody.rows.length;
    for (var r = length; r < length + 1; r++) {
        var row = tbody.insertRow(r);
        // etc.
    }
}


回答2:

Creating the string for the row and appending that to the tbody works, and from the docs it looks like the intended use for appendTo().

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 2; r++) {
        var row = tbody.insertRow(r);
        var rowtext = '<tr>';
        for (var c = 0; c < 4; c++) {
            rowtext += '<td><input type="text" size="1" value="x" /></td>';
        }
        rowtext += '</tr>';
        $(rowtext).appendTo(tbody);
    }
}