从javascript向div添加内容

时间:2012-08-16 14:45:59

标签: javascript jquery html

我想在我的html页面上加载包含div内容的脚本。我知道这是可能的,但我很难理解如何做到这一点。这是我的HTML:

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

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

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

}
showText()

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

4 个答案:

答案 0 :(得分:3)

您的代码是jQuery:

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

,您不需要$("#helloWorld").show();

在纯JavaScript中,

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

但请记住在DOM中加载div后调用showText()! (例如,在</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>";
}

答案 1 :(得分:1)

我认为它没有做任何事情(我假设),因为你的脚本标签在div本身之前。 如果您正在使用JQuery,则应将初始代码放入ready函数中,在您的情况下:

$(document).ready(function(){
  showText();
});

答案 2 :(得分:1)

加载脚本时,HTML元素“#helloWorld”仍然不存在。

像这样使用$(document).ready

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

答案 3 :(得分:0)

您尝试使用的语法需要JQuery。您可以在此处下载最新的JQuery库 http://jquery.com/

然后,您可以使用以下内容向div添加文本:

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

编辑:我已经在(文档)的开头添加了$字符,而且,你的div上没有必要使用.show()函数,因为它已经可见了。但是,如果您将div的显示设置为none,则应使用.show()显示div。