这是我的代码:
<div id="buttonscontainer">
<button class="button" id="add"></button>
<button class="button" id="remove"></button>
</div>
<main id="main">
<div class="rect"></div>
<div class="rect"></div>
</main>
脚本:
/*Calls the addRect function*/
window.onload=function() {
document.getElementById("add").onclick = addRect;
document.getElementById("remove").onclick = removeRect;
}
/*defines the behaviour of the onclick*/
function addRect(){
document.getElementById("main").innerHTML +='<div class="rect"></div>';
}
/*defines the behaviour of the onclick*/
function removeRect(){
document.getElementById("main").innerHTML -='<div class="rect"></div>';
}
答案 0 :(得分:0)
这是你想要实现的目标吗?
<强> HTML 强>
<div id="buttonscontainer">
<button class="button" id="add" onClick="addRect();">add</button>
<button class="button" id="remove" onClick="removeRect();">remove</button>
</div>
<main id="main">
<div class="rect">bla</div>
<div class="rect">ble</div>
</main>
<强> JS 强>
function addRect(){
var x = '<div class="rect">bli</div>';
document.getElementById("main").innerHTML += x;
}
function removeRect(){
var main = document.getElementById("main");
if (main.children.length > 0) {
main.lastChild.remove();
}
}