我试图理解为什么我可以将某些项目添加到单元格(如“id”),而不是其他项目(如onclick)。我的目标是按下一个按钮,它向表格添加一行(工作) - 并在生成/附加到表格上设置一些值。我注意到我可以进入控制台并执行以下操作:通过函数将事件分配给单元格
rows [row _#]。cells [cell _#]。id ='foo';
并让它出现在表和函数上;但以下内容不会出现在:
rows [row _#]。cells [cell _#]。onclick ='callEvent(this)';
我应该分配这个不同吗?
<button type="button" id="btn_add_row" onclick="addRow()">Add Row</button>
<table class="table table-hover" id="sample_table">
<thead>
<th>Column A</th>
<th id='calculate'>Column B</th>
</thead>
<tbody>
<tr>
<td>Item 1</td>
//sample of the td I'd like the function to generate
<td id='calculate' onclick='callEvent(this)'>Item 2</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
// Code to add a row to the table and assign properties to new row
function addRow() {
var table = document.getElementById("sample_table");
var lastRow = table.length;
var numberOfCols = table.rows[0].cells.length;
var row = table.insertRow(lastRow);
for (var i=0;i<numberOfCols;i++) {
row.insertCell(i);
if (table.rows[0].cells[i].id === 'calculate') {
// The calculate id will appear on the TD after running
table.rows[i].id = 'calculate';
// The onclick event will not appear on the TD afer running
table.rows[i].onclick='callEvent(this)';
}
function callEvent(element) {
console.log('Calculate event fired!');
}
</script>
是'onclick'你想添加一个字符串上面?这必须是一个功能。尝试'onclick = callEvent'。 – Jorg