【问题标题】:How to print table rows data in console如何在控制台中打印表格行数据
【发布时间】:2020-08-14 16:23:51
【问题描述】:

我已经使用 javascript for 循环创建了动态表行,我想触发一个点击事件 以一种方式在行上,每当用户单击任何行时,它都应该在控制台日志中可见。

<tbody>
<script>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
}
</tbody>
</script>

我知道这有很多答案,但我试过了,但没有一个能帮助我,还有一些打印出来的 未定义。

这是我尝试过的:

var table = document.getElementById("tableID");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}

【问题讨论】:

标签: javascript html


【解决方案1】:

您的 javascript 代码在我看来是正确的,但我认为您没有将其放置在正确的位置。

试试这个:

<script>
for(var i=0;i<data.length;i++){
    document.write("<tr>");
    document.write("<td>"+data[i]['col1']+"</td>");
    document.write("<td>"+data[i]['col2']+"</td>");
    document.write("<td>"+data[i]['col3']+"</td>");
    document.write("<td>"+data[i]['col4']+"</td>");
    document.write("<td>"+data[i]['col5']+"</td>");
}



function tableText(tableRow) {
  var name = tableRow.childNodes[1].innerHTML;
  var age = tableRow.childNodes[3].innerHTML;
  var obj = {'name': name, 'age': age};
  console.log(obj);
}


let tableData = document.getElementById('tableID').getElementsByTagName('tbody')[0]; 
for (let i = 0; i < tableData.rows.length; i++)
    {
        tableData.rows[i].onclick = function()
        {
            tableClicked(this);
        };
    }                       

function tableClicked(rowData) {
    let msg = rowData.cells[0].innerHTML+'*'+rowData.cells[1].innerHTML+'*'+rowData.cells[2].innerHTML+'*'+rowData.cells[3].innerHTML+'*'+rowData.cells[4].innerHTML;
    console.log(msg,data);
};
</script>

【讨论】:

  • 小心使用.getElementsByTagName('tbody')[0],因为你不知道提问者已经在他的表格中声明了这个标签。
  • @Reporter 好点,我应该仔细阅读问题!
  • @Ran 如果这有效,这意味着你使用了tbody 标签你能更新问题吗?
【解决方案2】:

您的 Javascript 代码在我看来是正确的,并且假设我在桌子上使用 tableText = console.log 时为我打印了正确的行。

虽然我在您的表格创建代码中注意到您没有使用 &lt;/tr&gt; 关闭表格行。

for(var i=0;i<data.length;i++){
  document.write("<tr>");
  document.write("<td>"+data[i]['col1']+"</td>");
  document.write("<td>"+data[i]['col2']+"</td>");
  document.write("<td>"+data[i]['col3']+"</td>");
  document.write("<td>"+data[i]['col4']+"</td>");
  document.write("<td>"+data[i]['col5']+"</td>");
  document.write("</tr>");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-03-04
    • 2014-08-28
    相关资源
    最近更新 更多