获取 DOM 元素常见的方法
海边的小溪鱼 2022-07-14 Vue2jQuery
获取 DOM 元素常见的方法,以及 this.$nextTick 的应用
# 获取 DOM 元素常见的方法
<div class="box1">原生方法获取元素</div>
<div class="box2">jQuery获取元素</div>
<div class="box3" ref="mydiv">ref引用</div>
<div class="box4" @click=change()>target事件属性</div>
<script>
// 1. 原生方法获取元素
document.querySelector(".box1")
// 2. jQuery 获取元素
$(".box2")
// 3. ref 获取元素
this.$refs.mydiv
// 4. target 属性获取元素(事件都会有一个默认的事件对象,里面有很多属性和方法)
change(e) {
console.log(e.target);
}
// 获取 父元素、子元素、兄弟元素的方法(el表示已获取到的元素)
el.parentNode // 父级
el.Children[0] // 子级
el.nextSibling // 兄弟级
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# this.$nextTick() 的应用
this.$nextTick 作用:等 DOM 结构渲染完成后,再执行回调函数里面的代码
注意:在 created 生命周期函数中,如果需要操作DOM元素,一定要写在 this.$nextTick() 回调函数中
<div class="box3" ref="mydiv">ref引用</div>
<script>
export default {
// 注意:在 created 生命周期函数中,数据已经有了,但是页面结构还未被渲染
created() {
// this.$nextTick 表示:等 DOM 结构渲染完成后,再执行回调函数里面的代码
this.$nextTick(() => {
this.$refs.mydiv.style.color = "blue"
})
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13