我有一个 Html 表,我正在为该表提供来自 firebase 的数据,所以在我的 Html 中,我没有td尝试在单击表行时添加表数据tr,但这是在添加对表头的单击th
<div>
<table>
<tr onclick="myFunction(this)">
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tbody id="table">
</tbody>
</table>
</div>
<script>
function myFunction(x) {
alert("Row index is: " + x.rowIndex);
}
</script>
第二次尝试是js我已经尝试过这个和许多其他类似的功能,但它什么也没做 没有响应 没有错误
function addRowHandlers() {
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
td这就是我从火力基地喂食的方式
var ref = firebase.database().ref("users");
ref.on("value", function(data){
$('#table').empty()
var content = '';
data.forEach(function(childSnapshot){
if (childSnapshot.exists()){
var childData = childSnapshot.val();
console.log(childData);
content +='<tr>';
content += '<td>' + childData.username + '</td>';
content += '<td>' + childData.phone + '</td>';
content += '<td>' + childSnapshot.key + '</td>';
content += '</tr>';
};
});
$('#table').append(content);
});
如何将 onClick 事件添加到每一行我是 HTML 和 js 语言的新手