知识点包括:createTextNode;createElement的;this问题;removeChild;getElementsByTagName
心得:对方法的记忆不够深刻;this问题没有解决。
body
<h3>单击下面的“添加”按钮添加标签</h3>
<div id="fuhezi"></div>
<div id="allclear" onclick="allqin()">全部清除</div>
<div id="one">
<span>aaaaaa</span>
<span id="oneBox" onclick="onetian('aaaaaaX')">添加</span>
</div>
<div id="one">
<span>bbbbbb</span>
<span id="oneBox" onclick="onetian('bbbbbbX')">添加</span>
</div>
css代码:
<style>
*{
margin: 0px;
padding: 0px;
}
body {
background-color: #002C50;
}
h3 {
color: white;
margin-left: 500px;
}
#fuhezi {
margin-top: 20px;
margin-left: 500px;
width: 350px;
padding: 10px 0;
background-color: white;
cursor: pointer;
}
#allclear {
background-color: tomato;
width: 100px;
height: 20px;
line-height: 20px;
text-align: center;
color: white;
margin-left: 500px;
margin-top: 20px;
border-radius: 3px;
cursor: pointer;
}
#one {
margin-left: 500px;
margin-top: 20px;
color: white;
}
#oneBox {
display: inline-block;
background-color: tomato;
width: 60px;
height: 20px;
margin-left: 30px;
line-height: 20px;
text-align: center;
border-radius: 3px;
cursor: pointer;
}
#fuhezi::after{
clear: both;
content: '';
display: block;
}
#fuhezi div {
float: left;
width: 70px;
height: 20px;
color: white;
text-align: center;
background-color: #349950;
margin: 2px 2px;
}
</style>
Js代码
<script>
function onetian(str){
let str1 = document.createTextNode(str);
let div = document.createElement("div");
div.appendChild(str1);
let fuhezi =document.getElementById("fuhezi");
div.onclick = function(){
this.parentNode.removeChild(this);
}
fuhezi.appendChild(div);
}
function allqin(){
let alldiv = fuhezi.getElementsByTagName('div');
console.log(alldiv);
for(let i=0;i<alldiv.length;i++){
fuhezi.removeChild(alldiv[i]);
i--;
}
}
</script>