我想在我的 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/