InnerHTML改变旧变量

时间:2017-10-19 15:59:05

标签: javascript html-table refresh innerhtml clear

我正在做一个在JS中创建表的函数。 我创建了一个变量 table_row 填充它,然后将 table_layout.appendChild(table_row); 添加到 table_layout 元素。 接下来,我通过 table_row 清除 innerHTML='' ,但在清理时,我 ALREADY 的变量已添加到元素 table_layout 也已清除

为什么会这样? 是否应该清除添加的元素? 如何避免这种情况? 请查看 CODE



var columns = ["col1", "col2", "col3"];
var rows = 5;

function Table() {
  var table_layout = document.createElement("table");
  var table_row = document.createElement("tr");

  for (var i = 0; i < columns.length; i++) {
    // main row
    table_row.innerHTML += "<th>" + columns[i] + "</th>";
  }

  table_layout.appendChild(table_row); //add in table element

  // table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
  
  //refresh table_row html, that would generate a new line
  //But when cleaning. Cleared in the previously added item in table_layout .... how??

  
  
  // 		 for (var j = 0; i < columns.length; j++) {
  // 		 		table_main_row.innerHTML += '<td></td>';
  // 		 	}

  // 		 for (var i = 0; i < rows; i++) {
  // 		 	table_layout.appendChild(table_row);
  // 		 }

  return table_layout;
}

var div = document.getElementById("qqq");
div.appendChild(Table());
&#13;
#qqq {
  background: red;
}
&#13;
<div id="qqq"></div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

table_row变量包含引用。您需要为每一行创建一个新元素。

// creates a DOM Element and saves a reference to it in the table_row variable
var table_row = document.createElement("tr");

// updates the DOM Element through the reference in the table_row variable
table_row.innerHTML += "<th>" + columns[i] + "</th>";

// still references the DOM Element, so you are clearing its content
// table_row.innerHTML = "";

你需要。 。

// create a new DOM Element to use
table_row = document.createElement("tr");
// then update its contents
table_main_row.innerHTML += '<td></td>';

。 。 。每次迭代。

有关教程,参考资料等内容,请参阅JavaScript on MDN

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">

var columns = ["col1", "col2", "col3"];
var rows = 5;

function createNewRow(headerRow)
{
    var newRowElem = null;

    try
    {
        newRowElem = document.createElement("tr");

        for (var i = 0; i < columns.length; i++) 
        {
            if(headerRow) newRowElem.innerHTML += "<th>" + columns[i] + "</th>";
            else newRowElem.innerHTML += "<td>" + columns[i] + "</td>";
        }

    }
    catch(e)
    {
        alert("createNewRow Error" + e.Message);
    }
    finally
    {

    }

    return newRowElem;
}


function Table() 
{
    var table_layout = null;

    try
    {
        table_layout = document.createElement("table");

        // Create Header Row
        table_layout.appendChild(createNewRow(true));

        // Create Other Rows
        for (var i = 0; i < rows; i++) 
        {
            table_layout.appendChild(createNewRow(false));
        }

    }
    catch(e)
    {
        alert("Table Error: " + e.Message);
    }
    finally
    {

    }

    return table_layout;
}

</script>

<style>
#qqq {
  background: red;
}
</style>
</head>
<body>

<div id="qqq"></div>

<script type="text/javascript" language="javascript">
    var div = document.getElementById("qqq");
    div.appendChild(Table());
</script>
</body>
</html>

答案 2 :(得分:0)

我这样做了。

var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');

var row = document.createElement('tr');
row.setAttribute('class', 'main_row');

for (var i = 0; i < this.fields.length; i++) { // строка с именами столбцов
	var th = document.createElement('th');
	th.setAttribute('class', 'cell_name');
	th.innerHTML = this.fields[i];
	row.appendChild(th);
}

table_layout.appendChild(row); //добавляем
row = document.createElement('tr'); // очищаем от старых элементов строку (переопределяем)
row.setAttribute('class', 'table_row');

var td = document.createElement('td');
	td.setAttribute('class', 'table_cell');
	// td.setAttribute('ondblclick', 'input_func()');
	td.addEventListener('click', function () {
		alert();
	});
	td.innerHTML='000';


for (var j = 0; j < this.fields.length; j++) { // создаем строку с N-количеством ячеек
	row.appendChild(td.cloneNode(true));
}

for (var i = 0; i < this.rows; i++) { // Добавляем её есколько раз через клона
	table_layout.appendChild(row.cloneNode(true));
}

但随后用表格的功能重新分配。

var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');

var row = table_layout.insertRow(0);
        var cell;

        for (var j = 0; j < this.fields.length; j++) { 
		 	cell = row.insertCell(j);
		 	cell.outerHTML = '<th>' + this.fields[j] + '</th>';
        	cell.className = 'cell_name';
		}

		for (var i = 0; i < this.rows; i++) { 
			row = table_layout.insertRow(i + 1);
            row.className = 'row_table';

		 	for (var n = 0; n < this.fields.length; n++) { 
		 		cell = row.insertCell(n);
		 		// cell.innerHTML = '00';
        		cell.className = 'table_cell';
        		cell.innerHTML = '&nbsp';
        	}
		}


		return table_layout;