1 'use strict'; 2 3 class View{ 4 5 constructor(){ 6 7 } 8 9 //创建html元素 10 addEl(fel, elemName, id, cls){ 11 //创建一个元素 12 let el = document.createElement(elemName); 13 //设置el id 和 class 14 if(id){el.setAttribute('id',id);} 15 if(cls){el.className = cls;} 16 //把el添加到fel并显示(渲染el) 17 if(fel){fel.appendChild(el);} 18 return el; 19 } 20 21 //删除html元素 22 delEl(){ 23 let k, arg = arguments, err = []; 24 for(k = 0; k < arg.length; k++){ 25 if(this.isEl(arg[k]) === false){err.push(arg[k]); continue;} 26 arg[k].parentNode.removeChild(arg[k]); 27 } 28 if(err.length > 0){return {err:'这里有一些删除失败的元素', arr:err};} 29 return true; 30 } 31 32 //id获取html元素 33 getEl(id){ 34 return document.getElementById(id); 35 } 36 37 //通过parentNode检查元素是否存在于页面中 38 isEl(el){ 39 if(typeof(el) !== 'object'){return false;} 40 //被删除之后的html元素object的 parentNode等于null 41 if(!el.parentNode){return false;} 42 return true; 43 } 44 45 //元素绑定事件 46 addEvent(target, callback){ 47 //target.addEventListener('click', function(event){if(callback){callback(event);}}, false); 48 } 49 50 } 51 52 let v = new View(); 53 54 console.log('创建元素'); 55 let el_a = v.addEl(document.body, "p"); 56 let el_b = v.addEl(document.body, "p"); 57 let el_c = v.addEl(document.body, "p"); 58 59 console.log('验证元素_0'); 60 console.log(v.isEl(el_a));//true 61 console.log(v.isEl(el_b));//true 62 console.log(v.isEl(el_c));//true 63 64 console.log('删除元素_0'); 65 console.log(v.delEl(el_a, el_b)); 66 console.log(v.delEl(el_c)); 67 68 console.log('验证元素_1'); 69 console.log(v.isEl(el_a)); 70 console.log(v.isEl(el_b)); 71 console.log(v.isEl(el_c)); 72 73 console.log('删除元素_1'); 74 console.log(v.delEl(el_a, el_b)); 75 console.log(v.delEl(el_c));