在 div 中添加 div

Adding a div inside a div

CSS:

#space{
    float: left;
    width: 500px;
    height: 500px;
    background:blue;
    }
#button{
    float: left;
    width: 200px;
    height: 500px;
    background:red;
    cursor: pointer;
}
#box{
    width: 100px;
    height: 100px;
    background: white;
}

html:

<div id="space"></div>
<div id="button"></div>

javascript:

$("#button").click(function(){
    $("#space").append($('#box'));
});

我尝试在每次点击 div "button" 时将 div "box" 添加到 div "space"。但是代码不是 working.Can 有人说是什么错误吗?

你很接近,但现在 Javascript 不知道 #box 是什么。要在按下按钮时将 <div> 添加到 <div>,请执行此操作(您已关闭):

$("#button").click(function(){
  $("#space").append('<div></div>');
});

请记住,id 必须是唯一的,因此请尝试使用 class,并调整 CSS 以瞄准 class :

// Javascript
$("#button").click(function(){
  $("#space").append('<div class="box"></div>');
});

// CSS
.box{
    width: 100px;
    height: 100px;
    background: white;
}

希望对您有所帮助!

编辑

使用 OP 的基本代码和 #box 存在的有趣观察:

// Before Click
<div id="space">Space</div>
<div id="box">Box</div>
<div id="button">Button</div>

// After Click
<div id="space">Space
  <div id="box">Box</div>
</div>
<div id="button">Button</div>

它的工作原理是将 #box 移动到 #space 内,并且不会创建新的 #box 对象。因此,与其说是增加,不如说是移动。

当使用 $('#box') 时,您告诉 jQuery 在您的 DOM 中查找带有 id='box' 的元素,如果它不存在,您将不会附加任何东西。

您的网站上有#box 元素吗?
否则你可以试试这个:

$("#button").click(function(){
  $("#space").append('<div id="box"></div>');
});

您正在尝试附加 id,但在加载页面时该页面上并不存在。您需要使用 id 的 "box":

创建 div
$("#button").click(function(){
  $("#space").append('<div id="box"></div>');
});

FIDDLE