javascript - 从javascript向div添加内容

标签 javascript jquery html

我想在我的 html 页面上加载一个包含 div 内容的脚本。我知道这是可能的,但我正在努力了解如何去做。这是我的 html:

<html>
<body>
<script src="script.js"> </script>
<div id="helloWorld"> </div>
</body>
</html>

为了让 html 页面显示某些内容,script.js 必须是什么?我在想这样的事情(我知道这是不正确的,我是 javascript 的初学者。

function showText()
{
    $("#helloWorld").html("<p> Hello World! </p>")
    $("#helloWorld").show();

}
showText()

有人可以告诉我我是否在正确的轨道上,我该如何解决这个问题?谢谢, 山姆

最佳答案

你的代码是 jQuery:

$("#helloWorld").html("<p> Hello World! </p>")
$("#helloWorld").show();

而且你不需要$("#helloWorld").show(); .

在纯 JavaScript 中,

function showText()
{
    document.getElementById("helloWorld").innerHTML="<p> Hello World! </p>";
}
showText()

但记得调用showText()在 DOM 中加载 div 之后! (例如,在 </body> 标签之前调用它)。

然后,

<html>
<head>
...
<script type="text/javascript" src="script.js"></script>
...
</head>
<body>
...
<script type="text/javascript">
showText();
</script>
</body>
</html>

和 script.js:

function showText(){
    document.getElementById("helloWorld").innerHTML="<p> Hello World! </p>";
}

关于javascript - 从javascript向div添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989772/

相关文章:

javascript - 如何在php中实现多个复选框

javascript - AES 在 CryptoJS 中加密并在 Coldfusion 中解密

javascript - 在 <head> 中(在函数/类中)使用 jquery append()

jQuery (文档).ready(函数($)

javascript - jQuery 鼠标进入/离开未正确检测悬停区域

javascript - 如何获取documentFragment中的子节点?

javascript - 如何通过 FTP 客户端将单独的 HTML 文件上传到 wordpress 站点?

Javascript 从 mySQL 输出到 'find and replace'

javascript - 将 JS 变量等同于 json 编码的 php 数组值,无论索引如何

javascript - 如何正确定义 jQuery 函数