简体   繁体   English

我的JS没有操纵HTML元素

[英]My JS Is Not Manipulating the HTML Elements

I am trying to write code to put one image on a whole set of elements but allow a click to reveal certain images in certain elements. 我正在尝试编写代码以将一个图像放置在整个元素集上,但是允许单击以显示某些元素中的某些图像。

So far, my JS hasn't changed any of the elements. 到目前为止,我的JS尚未更改任何元素。 If someone could look at it and give me suggestions, I would be very appreciative. 如果有人可以看一下并给我建议,我将不胜感激。

 const cards = document.querySelectorAll(".card"); const flipAllCards = function() { for (const card of cards) { card.innerHTML = `<img src="img/cardback.jpeg" alt="">`; } }; flipAllCards(); function assignImages() { for (const card of cards) { const cardName = card.id; const imageName = `${cardName}.jpeg`; function flipCard(card) { card.innerHTML = `<img src="img/${imageName}" alt="">`; return card.innerHTML; } console.log(flipCard(card)); card.addEventListener('click', function() { flipCard(card) }); } } assignImages(); 
 <div class="table"> <div class="card" id="agentbrown"><img src="img/agentbrown.jpeg" alt=""></div> <div class="card" id="agentjones"><img src="img/agentjones.jpeg" alt=""></div> <div class="card" id="agentsmith"><img src="img/agentsmith.jpeg" alt=""></div> <div class="card" id="spoonboy"><img src="img/spoonboy.jpeg" alt=""></div> <div class="card" id="switch"><img src="img/switch.jpeg" alt=""></div> <div class="card" id="trinity"><img src="img/trinity.jpeg" alt=""></div> </div> 

One way to do it is make "card" class have a same "background-image" in CSS for all your cards while having empty divs. 一种实现方法是让“ card”类在CSS中为所有卡片具有相同的“ background-image”,同时使divs为空。 And then just add card.innerHTML images with corresponding ID's in JS when you need to flip a card 然后,当您需要翻转卡片时,只需在JS中添加具有相应ID的card.innerHTML图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM