简体   繁体   English

用javascript附加到正文

[英]Appending to body with javascript

I have an assignment to make several bugs fly around the screen randomly, but I'm having problems getting divs to be added to the html body through javascript. 我的任务是使多个错误随机在屏幕上飞来飞去,但是我在通过javascript将div添加到html主体时遇到了问题。

<head>
<title>Fly little bug! Fly!</title>

<script type="text/javascript">
/* <![CDATA[ */
var numBugs = 0;
var body = document.getElementsByTagName("body");
function bug(startX, startY, xSpeed, ySpeed){
  var self = this;
  this.xPos = startX;
  this.yPos = startY;
  this.xSpeed = xSpeed;
  this.ySpeed = ySpeed;
  this.divId = "bug" + numBugs;

  this.div = document.createElement("div");

  this.div.innerHTML = "test";

  body.appendChild(self.div);

  this.fly = function(){
    self.xPos += self.xSpeed;
    self.yPos += self.ySpeed;
  }
  this.fly();
  this.flyInterval = setInterval(function(){ self.fly(); },5000);
  numBugs++;
}

/* ]]> */
</script>
</head>

<body onload = "var bug1 = new bug(10, 20, 5, 3);">

</body>
</html>

I can see two problems. 我可以看到两个问题。

  1. The getElementsByTagName function returns an array of elements. getElementsByTagName函数返回元素数组。 You have to be explicit that you want the first element of the array. 您必须明确表示想要数组的第一个元素。

     var body = document.getElementsByTagName("body")[0]; 

    You're essentially saying "give me all the tags in the document of type 'body'". 您实际上是在说“给我'body'类型的文档中的所有标签”。 It gives you a list of tags, and you have to get the first one even though there should only be one "body" in any HTML document. 它为您提供了一个标签列表,即使在任何HTML文档中应该只有一个“ body”,您也必须获得第一个标签。 The [0] in the code above gives you the first one. 上面代码中的[0]给您第一个。

  2. You are trying to access the body before it's created. 您试图在创建主体之前对其进行访问。 The <script> occurs in the document before the <body> tag, so at the time the script is executed, the body doesn't exist. <script>出现在文档中的<body>标记之前,因此在执行脚本时,主体不存在。 You need to move the call to getElementsByTagName inside the bug() function. 您需要将调用移到bug()函数内的getElementsByTagName上。

document.body.innerHTML += '<div>Div Content</div>';

如果您想使自己更容易进行简单的DOM操作,请查看jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM