DOM操作

1,090 阅读1分钟

1. dom操作性能

 缓存dom,每次获取所有的dom循环时,都插入一个变量中,不用每次都计算dom的长度

2. for循环插入dom节点

先创建文档片段,先把循环出来的dom都插入文档片段中,然后再把片段插入dom中

示例

创建文档片段 document.createDocumentFragment()

const frag = document.createDocumentFragment()

for(let i = 0; i < 10; i++) {

const div = document.createElement('div')

div.innerHTML = `我是div${i}`

frag.appendChild(div)

}

//都完成时,再 插入dom中

const list = []

list.appendChild(frag)

设置属性,获取属性,

  ele.setAttribute('data-name', '张三')

  ele.getAttribute('data-name')

通过元素直接获取属性名称,只能是,原始存在的属性才能获取

设置元素的class

ele.className = 'layout'

ele.className 都是覆盖的设置,会把之前的class清空,再设置

ele.classList  = 'name city'

ele.className = 'aa bb dd'

ele.classList.contains('name')  判断当前元素是否有这个class

ele.classList.add('name')  //添加一个或多个类

ele.classList.remove('name') //删除一个或多个类

ele.dataType = 1 元素节点

ele.dataType = 3 文本节点

原型

Object.create(null) 没有原型。原型指向空

 function People() {

console.log("thiAAs", this)

this.name = "张三"

}

People.prototype.say = function() {

console.log("大家都说话")

}

 function Student() {

   People.apply(this); //调用基类的构造函数 这里是继承构造函数的属性方法,不是原型的属  性和方法

   this.city = "成都"

}

Student.prototype = Object.create(People.prototype); 把student的原型指向people

Student.prototype.constructor = Student  增加构造函数

Student.prototype.eat = function() {

   console.log("学生吃饭")

}

Object.create() 相当于有原型指向的概念,是一层一层的,不像直接赋值prototype这种放在一起,不规范,这种也是class的设计方式

通过class继承的方法,静态属性,和方法也可以继承 static定义的属性,方法