gpt4 book ai didi

javascript - 使用 innerHTML 构建动态表

转载 作者:行者123 更新时间:2023-11-29 21:03:17 26 4
gpt4 key购买 nike

我正在尝试使用 innerHTML 在 javascript 中构建一个动态表。

当网络应用程序运行时,它只打印 console.log,但不构建表。

我尝试了两种方式:

首先:

    success: function (data, status, jqXHR) {


$.each(data, function (index, dati) {

console.log(dati)


var html = "<table width=\'450\' bgcolor=\'white\' border=\'2\' bordercolor=\'black\' cellpadding=\'10\' cellspacing=\'1\'>\n" +
" <tr style=min-width:850px>\n" +
" <td>dati.codiceCOmmessa </td>\n" +
" <td>dati.commessaMainSub</td>\n" +
" <td>dati.settoreCliente</td>\n" +
" <td>dati.nomeCliente</td>\n" +
" <td>dati.titoloQuals</td>\n" +
" <td>dati.keyWordsTopic</td>\n" +
" <td>dati.keyWordsActivities</td>\n" +
" <td>dati.anno</td>\n" +
" <td>dati.dataInizio</td>\n" +
" <td>dati.dataFine</td>\n" +
" <td>dati.referente</td>\n" +
" <td>dati.referenteDoc</td>\n" +
" <td>dati.sviluppatore</td>\n" +
" <td>dati.path</td>\n" +
" </tr>\n" +
"</table>"

html.innerHTML;
})
},

第二个:

(使用 body.innerHTML 或 node.innerHTML,应用出错):

    success: function (data, status, jqXHR) {


$.each(data, function (index, dati) {

console.log(dati)

innerHTML = "<table width=\'450\' bgcolor=\'white\' border=\'2\' bordercolor=\'black\' cellpadding=\'10\' cellspacing=\'1\'>\n" +
" <tr style=min-width:850px>\n" +
" <td>dati.codiceCOmmessa </td>\n" +
" <td>dati.commessaMainSub</td>\n" +
" <td>dati.settoreCliente</td>\n" +
" <td>dati.nomeCliente</td>\n" +
" <td>dati.titoloQuals</td>\n" +
" <td>dati.keyWordsTopic</td>\n" +
" <td>dati.keyWordsActivities</td>\n" +
" <td>dati.anno</td>\n" +
" <td>dati.dataInizio</td>\n" +
" <td>dati.dataFine</td>\n" +
" <td>dati.referente</td>\n" +
" <td>dati.referenteDoc</td>\n" +
" <td>dati.sviluppatore</td>\n" +
" <td>dati.path</td>\n" +
" </tr>\n" +
"</table>"


})
}

有人可以帮我告诉我我做错了什么吗?

最佳答案

起初,循环可以使事情变得更简单(字符串文字也是如此),因此可以简单地显示所有对象值:

var html = 
`<table width='450' bgcolor='white' border='2'bordercolor='black' cellpadding='10' cellspacing='1'>
<tr style='min-width:850px'>
${
Object.values(dati)
.map(
value => `<td>${value}</td>`
).join("\n")
}
</tr>
</table>`;

或者,如果您不喜欢文字,同样适用于连接:

var html =     
"<table width='450' bgcolor='white' border='2'bordercolor='black' cellpadding='10' cellspacing='1'><tr style='min-width:850px'>"
+ Object.values(dati)
.map(
value => "<td>"+value+"</td>"
).join("\n")
+ "</tr></table>";

你可能想用 html 做某事:

document.body.innerHTML += html;

A small demo

关于javascript - 使用 innerHTML 构建动态表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com