jQuery can I use append/appendTo in this javascript function

女生的网名这么多〃 提交于 2019-12-25 01:07:14

问题


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);
    }
}


来源:https://stackoverflow.com/questions/5254283/jquery-can-i-use-append-appendto-in-this-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!