简体   繁体   中英

Target multiple div ID in the same function/event

I'm trying to run a function to allows several divs, each with it's own unique ID, in the same call. I thought this would work:

 var btn1 = document.getElementById("btn1"); btn1.onmouseover = function(event){ event.preventDefault(); toggleDivs("ed1", "ed2", "ed3"); }; //function to hide or show function toggleDivs(s){ //reset document.getElementById("ed1").classList.remove("shown"); //show document.getElementById(s).classList.add("shown"); }

It kind of works, but only the first div in the array (ed1) appears. The other two and I'm sure any more if I added them to the overall array, would not.

I tried having a toggleDivs for each div to appear (3 in all in this case), but no luck. What would be the way to get these to all appear at once instead of just the first one?

In toggleDivs you are only using the first parameter. Use an array to send all:

 toggleDivs([ "ed1", "ed2", "ed3" ]);

The document.getElementById(id) function only receives one id at a time, so you have to iterate like this:

 s.forEach(id => document.getElementById(id).classList.add("displayed"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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