当通过js去改变DOM结构时: document.getElementByClassName会更新旧的查询结果,document.querySelectorAll则不会。 注:querySelectorAll()的参数是一个css选择器。
<template>
<div class="box">
<div class="zdy">1</div>
<div class="zdy">2</div>
<div class="zdy">3</div>
<div class="zdy">4</div>
<div class="zdy">5</div>
</div>
</template>
mounted() {
let items = document.getElementsByClassName("zdy");
console.log(items.length);
let appendNode = document.createElement("div");
appendNode.classList.add("zdy");
document.querySelector('.box').appendChild(appendNode)
console.log(items.length);
},
<template>
<div class="box">
<div class="zdy">1</div>
<div class="zdy">2</div>
<div class="zdy">3</div>
<div class="zdy">4</div>
<div class="zdy">5</div>
</div>
</template>
mounted() {
let items = document.querySelectorAll(".zdy");
console.log(items.length);
let appendNode = document.createElement("div");
appendNode.classList.add("zdy");
document.querySelector('.box').appendChild(appendNode)
console.log(items.length);
},
|