element.remove() 似乎很奇怪。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
</body>
<script>
class View {
constructor() {
this.parent = document.querySelector('#root')
}
template() {
return `
<div>Random Num</div>
<div>${Math.random()}</div>
<button type='button'>Reset Random Num</button>
`
}
render() {
const templateElement = document.createElement('template')
templateElement.innerHTML = this.template()
templateElement.content
.querySelector('button')
.addEventListener('click', () => {
this.rerender()
})
this.parent.append(templateElement.content)
}
rerender() {
this.parent.childNodes.forEach((item) => {
// here is the problem
item.remove()
})
// const templateElement = document.createElement('template')
// templateElement.innerHTML = this.template()
// this.parent.append(templateElement.content)
}
}
const viewIns = new View()
viewIns.render()
</script>
</html>
當我單擊按鈕時,doms 根本沒有被洗掉,然后我再次單擊按鈕,只有 div 包含剩下的亂數,我真的很困惑為什么會這樣。
uj5u.com熱心網友回復:
childNodes回傳一個實時集合。使用實時集合可能不直觀,因為它們可能會在您迭代它們時自行變異并讓您失望。在這里,您正在.remove()創建一個文本節點,然后<div>Random Num</div>立即成為集合中的第 0 個索引。然后轉到集合中的第一個索引,這是另一個文本節點。該程序重復幾次,洗掉所有文本節點,但不洗掉任何元素。
首先將 childNodes 轉換為陣列,以便在您迭代它時集合不會改變。
[...this.parent.childNodes].forEach((item) => {
顯示代碼片段
class View {
constructor() {
this.parent = document.querySelector('#root')
}
template() {
return `
<div>Random Num</div>
<div>${Math.random()}</div>
<button type='button'>Reset Random Num</button>
`
}
render() {
const templateElement = document.createElement('template')
templateElement.innerHTML = this.template()
templateElement.content
.querySelector('button')
.addEventListener('click', () => {
this.rerender()
})
this.parent.append(templateElement.content)
}
rerender() {
[...this.parent.childNodes].forEach((item) => {
item.remove()
})
// const templateElement = document.createElement('template')
// templateElement.innerHTML = this.template()
// this.parent.append(templateElement.content)
}
}
const viewIns = new View()
viewIns.render()
<div id="root"></div>
或者,一種更簡單的方法是將.innerHTML父級設定為空字串。
this.parent.innerHTML = '';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487854.html
標籤:javascript html dom
下一篇:如何在正確的元素上執行功能?
