[英]how to add/remove div ,related to a specific class, onclick
im trying to use two buttons. 我试图使用两个按钮。 one to add a to the 'main' tag and the other to remove.
一个添加到“ main”标签,另一个删除。 when i leave only the addRect function in the code im able to add rect's to the 'main' section but when i add the removeRect all div's dissapear.
当我在代码中仅保留addRect函数时,无法将rect添加到“ main”部分,但是当我添加removeRect时,所有div都消失了。 why is that and isnt it working?
为什么会这样呢?
this is my code: 这是我的代码:
<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>
script: 脚本:
/*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>';
}
Is this what you're trying to achieve? 这是您要达到的目标吗?
Check JsFiddle Demo 查看JsFiddle演示
HTML 的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 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.