嗨,我尝试通过单击该 div 将新 div 添加到现有 div 中,我应该对新 div 执行相同的操作。例如,我有初始 div,当我单击它时,我在其中创建了不同的 div。然后我单击新的 div,并在其中创建了新的 div。我希望解释是可以理解的 =) 这是我的代码,
<script type="text/javascript" src="js/jquery-1.4.2.min.js">
function run(id){
var id = $(id).attr("id");
document.getElementById(id).onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "50px";
div.style.top = "50px";
div.style.height = "10px";
div.style.width = "10px";
document.getElementById(id).appendChild(div);
};
}
<style>
div.initial {
background-color:white;
width:400px;
height:30px;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class='initial' onclick='run(this)'>
//new div will come here
</div>
</body>
</html>
我的 javascript 无法正常工作的问题是,当我使用此代码单击 div 时,什么也没有。
最佳答案
你所追求的基本想法。
function run (){
var div = document.createElement("div"); //create new div
div.addEventListener("click", run); //bind click to new div
this.appendChild(div); //append the new div to clicked div
this.removeEventListener("click", run); //remove the original click event
}
document.getElementById("start").addEventListener("click", run); //bind the initial click event
html, body { height: 100%; }
div {
border: 1px solid black;
width: 90%;
height: 90%;
}
<div id="start"></div>
关于javascript - 使用 onClick() 将新的 div 添加到现有的 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32383726/