Javascript 如何添加/删除与特定类相关的div onclick
我试着用两个按钮。一个用于向“main”标记添加一个,另一个用于删除。 当我在代码中只保留addRect函数时,我可以将rect添加到“main”部分,但当我添加Remolect时,所有div都会消失。为什么会这样,它不起作用吗 这是我的代码:Javascript 如何添加/删除与特定类相关的div onclick,javascript,html,Javascript,Html,我试着用两个按钮。一个用于向“main”标记添加一个,另一个用于删除。 当我在代码中只保留addRect函数时,我可以将rect添加到“main”部分,但当我添加Remolect时,所有div都会消失。为什么会这样,它不起作用吗 这是我的代码: <div id="buttonscontainer"> <button class="button" id="add"></button> <button class="button" id
<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>';
}
/*调用addRect函数*/
window.onload=function(){
document.getElementById(“add”).onclick=addRect;
document.getElementById(“remove”).onclick=RemoveECT;
}
/*定义onclick的行为*/
函数addRect(){
document.getElementById(“main”).innerHTML+='';
}
/*定义onclick的行为*/
函数{
document.getElementById(“main”).innerHTML-='';
}
这就是你想要实现的目标吗
检查
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>
添加
去除
布拉
ble
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();
}
}
函数addRect(){
变量x='bli';
document.getElementById(“main”).innerHTML+=x;
}
函数{
var main=document.getElementById(“main”);
如果(main.childrence.length>0){
main.lastChild.remove();
}
}
您能使用JQuery吗?不……我正在寻找纯javascript解决方案查看控制台,看看它说了什么。提示:控制台是否说明了NaN
?JavaScript中的字符串没有-=
(通常是-
)。