使用 VanillaJS 类 obj 永久创建 DOM 元素?(.insertAdjacentElement)



>我创建了一个新的 H4 元素,该元素按预期在 DOM 中呈现。但问题是,该元素不会永久渲染。

单击另一个图像(只有 2 个图像标签(突然将 H4 元素添加到下一个图像,但删除另一个图像。我环顾四周,找不到相关的话题。

我感谢您的帮助。

class Player {
constructor() {
// Add elements and content for clicks.
this.addHeader = document.createElement("h4");
this.text = document.createTextNode('The number of times you have clicked:')
this.addHeader.appendChild(this.text);
console.log(this.addHeader);
// Obtain images from HTML.
this.images = document.querySelectorAll('.cat-image');
}
// Update when the image is clicked.
update() {
for (const image of this.images) {
let compareSrc = image.attributes.getNamedItem('src'),
ifcontainsH4 = Array.from(image.parentElement.childNodes).includes('h4');
image.addEventListener('click', (e) => {
(compareSrc === compareSrc) && !ifcontainsH4
? image.parentElement.insertBefore(this.addHeader, image.parentElement.children[1])
: console.log('Parent element contains a h4 tag.');
e.preventDefault();
})
}
}
}
// Instance of class Player.
const player = new Player();
// Loop for event listeners that are apart of a class.
(function loop() {
player.update();
})(this)

this.addHeader在构造Player时运行,每次点击都会引用它。因此,它只是将相同的 h4 元素移动到每个单击的图像上。

如果您希望在每次单击时添加新的 h4,则每个单击处理程序都应创建自己的 h4 元素。

最新更新