セルに特定のアイテム(「id」など)を追加でき、onclickなどのアイテムを追加できない理由を理解しようとしています。私の目標は、テーブルに行を追加するボタンを押したままにして、テーブルに生成/追加された値を設定することです。私はコンソールにステップインして、次のようにすることができることに気づいた。セルに関数を介してイベントを割り当てる
行[行_#]。セル[セル_#]。id = 'foo';
これは、と関数の表に表示されています。しかし、以下は表示されません:
行[行_#]。セル[セル_#]。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