Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - How can I access the inner HTML of an element while looping over it with a class selector?

I am working on a project that has several paragraphs of text with keywords (set to overflow so you can scroll them in a text box). On hover, these keywords should populate another part of the page with images related to the keyword itself. My plan has been to put these keywords in spans with the same class name and then to select them all, using forEach to make each of them hoverable, and on hover to have them execute the popImage function.

This is where I'm stuck: I need popImage to be able to access the inner HTML of the specific keyword when it runs, so that it can compare that to the JSON list in which I'm storing the specific images that correspond to those keywords. Right now on my site, it is logging only the second keyword.

const popImage = () => {
  //this is where I'm hoping to make images load in to another div.
  console.log(name) //for testing to see if I can compare the value of name (stringified) to a list of object names and grab the images from the matching one.
}

//make keywords hoverable and run popImage
list = document.querySelectorAll(".keyword");

list.forEach((item)=>{
  name = item.innerHTML; //I think this is the problem but couldn't figure out how else to do it.
  item.addEventListener("mouseover", popImage);});
<div id="text">
      Hovering over the word <span class="keyword">horse</span> should populate a separate div with images of horses, while hovering over <span class="keyword">dog</span> should populate it with images of dogs.
</div>
question from:https://stackoverflow.com/questions/65909694/how-can-i-access-the-inner-html-of-an-element-while-looping-over-it-with-a-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can do that, by using event in popImage

const popImage = (e) => {
  console.log(e.target.innerHTML);
}

const list = document.querySelectorAll(".keyword");
list.forEach((item) => {
  item.addEventListener("mouseover", popImage);
});
.keyword {
    font-weight: bold;
}
<div id="text">
  Hovering over the word <span class="keyword">horse</span> should populate a separate div with images of horses, while hovering over <span class="keyword">dog</span> should populate it with images of dogs.
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...