Adding content to a table row () with javascript?

后端 未结 2 1464
天涯浪人
天涯浪人 2021-01-05 17:42

I have a table as follows:



        
      
      
      
2条回答
  •  臣服心动
    2021-01-05 18:02

    You can use the native insertCell() method to insert cells.

    Give this a try:

    Example: http://jsfiddle.net/VzTJa/

    var new_row = document.createElement('tr');
    new_row.insertCell(0).innerHTML = "test";
    new_row.insertCell(1).innerHTML = "test2";
    

    or you can accomplish it without your insertAfter() function by using insertRow() as well.

    Example: http://jsfiddle.net/VzTJa/1/

    var insert = document.getElementById("insert");
    var new_row = insert.parentNode.insertRow( insert.rowIndex + 1 );
    new_row.insertCell(0).innerHTML = "test";
    new_row.insertCell(1).innerHTML = "test2";
    

    Give this workaround a try:

    Example: http://jsfiddle.net/VzTJa/2/

    var temp = '
col 1col2
'; var close_temp = '
'; var temp_div = document.createElement('div'); var html_to_insert = 'testertester'; temp_div.innerHTML = temp + html_to_insert + close_temp; insertAfter(document.getElementById("insert"), temp_div.firstChild.firstChild.firstChild); temp_div.removeChild(temp_div.firstChild);

Basically creates a couple strings representing the opening and closing tags of a table. You concatenate it with your content, and set it as the innerHTMl of a temporary div, then fetch the row you want, and do an .appendChild().

There may be a better way, or you may find a way to improve this one.

I came up with this after glancing at a solution in this article from a guy who apparently worked on IE and is partly responsible for the parser.

提交回复
热议问题