0

我有一个 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 语言的新手

4

1 回答 1

0

您可以重构您的功能,例如

var ref = firebase.database().ref("users");
ref.on("value", function (data) {
    $('#table').empty()
    data.forEach(function (childSnapshot) {
        if (childSnapshot.exists()) {
            var childData = childSnapshot.val();
            console.log(childData);
            const tr = document.createElement('tr')
            let content = ""
            content += '<td>' + childData.username + '</td>';
            content += '<td>' + childData.phone + '</td>';
            content += '<td>' + childSnapshot.key + '</td>';

            tr.innerHTML = content;
            tr.onclick = function () {
                alert('tr', childData.phone)
            }
            $('#table tbody').append(tr);
        };
    });

});
于 2021-05-24T10:48:42.750 回答