gpt4 book ai didi

javascript - 使用 Javascript 函数将 HTML 写入屏幕

转载 作者:行者123 更新时间:2023-11-28 03:55:30 25 4
gpt4 key购买 nike

我是 JavaScript 和 HTML I 的新手,需要一些帮助!

我正在尝试用 JavaScript 编写一个表格,将其写入页面 HTML,然后将该函数导入 HTML 文件以显示该表格。

我在 JavaScript 文件中有这个

function createTable()
{
var table = "<table>";

table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";

document.write(table);

}

然后我指定 src 并在 html 文件中调用该函数,如下所示:

<head>
<script scr = "source/file.js" type=text/javascript"></script>
</head>

<body>
<script>
createTable()
</script>
</body>

虽然这有效,但我听说使用 document.write() 是一种非常糟糕的做法。

我试过使用 table = document.getElementById('tablePrint').innerHTML;然后在 HTML 文件中使用 <div id="tablePrint"></div>但是我的表没有显示。我也试过 document.body.appendChild(table);但这也不起作用。

正在使用 document.write()好的?或者他们是将我的表格写入屏幕上的 HTML 的更好方法。

最佳答案

您的示例中缺少一些双引号。我建议您使用 JQuery:

$(function() { // After the HTML content loads
var table = "<table>";

table += "<tr>";
table += "<th><center>Title</center></th>";
table += "</tr>";
table += "<tr>";
table += "<td><center> data </center></td>";
table += "</tr>";
table += "</table>";

$('body').append(table); // Appends HTML to an element
});

这是 fiddle .

here这就是为什么 document.write() 不是一个好的做法

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

希望对您有所帮助:)

关于javascript - 使用 Javascript 函数将 HTML 写入屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32582500/

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