Javascript Add Table Row

后端 未结 2 1826
暗喜
暗喜 2020-12-22 00:55

I\'m not sure how to add a row where I want it.



        
2条回答
  •  滥情空心
    2020-12-22 01:11

    Don't use innerHTML to modify tables, it will throw an error in most versions of IE. Use DOM methods.

    Don't use an A element when you don't want an link or anchor, use an element like a button or styled span.

    You can't add a TR element as a child of a DIV element, it's invalid. You must add it as a child of a table section element (thead, tbody or tfoot). In some cases you can add rows to a table element but some browsers don't like that either.

    So to create the new row, use:

    var tr = document.createElement('tr');
    var td = tr.appendChild(document.createElement('td'));
    
    // Much better to add a class and do this stuff with CSS
    td.style.valign = 'middle';
    var span = document.createElement('span');
    span.style.fontWeight = 'bold';
    span.appendChild(docment.createTextNode('URL ' + i);
    
    td = tr.appendChild(document.createElement('td'));
    var input = td.appendChild(document.createElement('input'));
    input.name = 'url' + i;
    input.type = 'text';
    input.size = '40'
    

    now append the TR to a table section somewhere.

    document.getElementById('myTable').tBodies[0].appendChild(tr);
    

    The whole thing looks like:

    
    
    
    Name:
    Password:
    URL:
    ETC:

    You could build the row to add in the bottom table and have it hidden, then just clone it and modify the bits that need it.

提交回复
热议问题