将Div插入另一个Div? [英] Inserting a Div Into another Div?

查看:151
本文介绍了将Div插入另一个Div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个网络应用程序,并想知道为什么以下代码不工作。它首先创建一个元素,然后将其添加到正文。然后我创建另一个Div元素,我想放在我创建的第一个div元素内。

Im creating a web app and would like to know why the following code is not working. It first creates a element which is then added to the body. I then create another Div element which i would like to place inside the first div element that i created.

我使用MooTools类来创建和初始化对象,它的工作正常我似乎无法获得以下代码。代码位于一个类中的 initialize:function()中:

Im using MooTools classes to create and initialize objects and it works fine but i just cant seem to get the following code to work. The code is inside aninitialize: function() of a class:

this.mainAppDiv = document.createElement("div");
this.mainAppDiv.id = "mainBody";
this.mainAppDiv.style.width = "100%";
this.mainAppDiv.style.height = "80%";
this.mainAppDiv.style.border = "thin red dashed";
document.body.appendChild(this.mainAppDiv); //Inserted the div into <body>
//----------------------------------------------------//
this.mainCanvasDiv = document.createElement("div");
this.mainCanvasDiv.id = "mainCanvas";
this.mainCanvasDiv.style.width = "600px";
this.mainCanvasDiv.style.height = "400px";
this.mainCanvasDiv.style.border = "thin black solid";
document.getElementById(this.mainAppDiv.id).appendChild(this.mainCanvasDiv.id);

您可以看到它首先创建一个名为mainBody的div,然后将其附加到document.body ,这部分代码工作正常。问题来自于创建第二个div并尝试使用 document.getElementById(this.mainAppDiv.id).i(this.mainCanvasDiv.id);

As you can see it first creates a div called "mainBody" and then appends it the document.body, This part of the code works fine. The problem comes from then creating the second div and trying to insert that usingdocument.getElementById(this.mainAppDiv.id).i(this.mainCanvasDiv.id);

任何人都可以想到上述代码不起作用的原因?

Can anyone think of a reason the above code does not work?

推荐答案

而不是:

document.getElementById(this.mainAppDiv.id).appendChild(this.mainCanvasDiv.id);

只要做:

this.mainAppDiv.appendChild(this.mainCanvasDiv);

这样你就直接附加了 mainCanvesDiv mainAppDiv 。如果您已经有一个元素的引用,则不需要 getElementById

This way you are appending the mainCanvesDiv directly to the mainAppDiv. There is no need to getElementById if you already have a reference to an element.

这篇关于将Div插入另一个Div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆