在JavaScript中创建带有onClick属性的行

Creating a row with onClick properties in JavaScript

本文关键字:onClick 属性 JavaScript 创建      更新时间:2023-09-26

我使用来自W3Schools的代码片段在我的表中创建一个新行:

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

创建它后,表中的所有行都有它们的onClick函数,除了我刚刚创建的那个,所以我的问题是,我如何为该行指定一个onClick函数?

也可以使用

document.getElementById("myTable").innerHTML+="<tr onClick='myFunc();'></tr>"

或者你也可以用

row.onClick="myFunc();"   

 row.setAttribute( "onClick", "javascript: myFunc();" )

或者稍后添加此事件侦听器:

var obj=document.getElementsByTagName("tr")[0]
obj.onclick=function(){alert("whatever")};

where [0] 0=行号