DOM操作案例
创建,删除案例
//JS
var tab = document.createElement("table"); //创建table标签
tab.border = 1;
document.body.appendChild(tab); //将table标签加到body里
var arr1 = [["小王","男","18",""],["小李","男","18",""],["小张","男","18",""],["大王","男","18",""]];
var arr2 = ["姓名","性别","年龄","删除"]
for(var i=0;i<arr1.length;i++){
var tr = document.createElement("tr");
if (i==0) {
for(var j=0;j<arr2.length;j++){
var th = document.createElement("th");
th.innerHTML = arr2[j];
tr.appendChild(th);
}
}else{
for(var k=0;k<arr1[0].length;k++){
var td = document.createElement("td");
td.innerHTML = arr1[i-1][k];
if(k==3){
td.innerHTML = "<a href='##' onclick = 'fn(this)'>删除</a>"
}
tr.appendChild(td);
}
}
tab.appendChild(tr);
}
document.body.addEventListener("mouseover",function(a){
if(a.target.nodeName == "TD"){
// alert(1)
var aa = a.target;
var bb = aa.parentNode;
bb.setAttribute("style","background:red");
// bb.style.background = "red";
}
});
document.body.addEventListener("mouseout",function(a){
if(a.target.nodeName == "TD"){
// alert(1)
// td.setAttribute("style","background:randomNum(16)")
var aa = a.target;
var bb = aa.parentNode;
bb.style.background = "white";
}
});
function fn(a){
tab.removeChild(a.parentNode.parentNode)
}
选项卡添加删除案例
//CSS
.float{
float: left;
}
//HTML
<div>
<input type="checkbox" class="float"><p id="text">hello world</p>
</div>
<button>删除</button>
//JS
var div = document.getElementsByTagName('div')[0];
var btn = document.getElementsByTagName('button')[0];
var p = document.getElementsByTagName('p');
var f = document.getElementsByClassName('float')[0];
var txt = document.getElementById('text');
var n=0;
var c = div.children;
var checks = document.getElementsByTagName('input'); //长度为1
txt.onclick = function(){
var oP = document.createElement("p");
oP.innerHTML = "hello";
opCopy = oP.cloneNode(true);
n++;
opCopy.innerHTML +=n;
var checkBox = document.createElement("input"); //创建复选框
checkBox.type = "checkbox";
opCopy.insertBefore(checkBox,opCopy.firstChild); //添加在opCopy前面
div.appendChild(opCopy);
checks = document.getElementsByTagName('input');
select(); //没点击一次 checks长度变化一次 ,因此每次必须更新checks的长度
}
btn.onclick = function(){
checks = document.getElementsByTagName('input');
var a = checks.checked;
for(var i = checks.length-1;i>0;i--){
var a = checks[i].checked;
if(a==true){
div.removeChild(checks[i].parentNode);
}
}
console.log(checks.length)
select(); //没点击一次 checks长度变化一次 ,因此每次必须更新checks的长度
}
f.onclick = function(){
var all = f.checked;
for(var i = checks.length-1;i>0;i--){
checks[i].checked = all;
}
console.log(checks.length)
}
function select(){
for(var i = 1;i<checks.length;i++){
checks[i].onclick = function(){
var flag = true;
console.log(checks.length)
for(var j =1;j<checks.length;j++){
if(!checks[j].checked){
flag = false
}
}
checks[0].checked = flag;
}
}
}
网友评论