简体   繁体   中英

html display property cant change using javascript

The script works fine for #myLinks but it's not working properly for #myLinks2.

The only thing working for #myLinks2 is the picture change
style

 function opentest(x) { var y = document.getElementById(x); if (y.style.display === "block") { if (x == 'myLinks') { document.getElementById('citypart').src = "pic/plus.png"; } if (x == 'myLinks2') { document.getElementById('roadpart').src = "pic/plus.png"; } y.style.display = "none"; } else { if (x == 'myLinks') { document.getElementById('citypart').src = "pic/minus.png"; } if (x == 'myLinks2') { document.getElementById('roadpart').src = "pic/minus.png"; } y.style.display = "block"; } }
 #myLinks { display: none; } #myLinks2 { display: none; }
 <a onclick="opentest('myLinks')" style="background-color:#ccc;color: white;"> <img id="citypart" src="pic/plus.png" height="42" width="42"> travel to </a> <div id="myLinks"> <a href="athen.php">----Athen</a> </div> <a onclick="opentest('myLinks2')" style="background-color:#ccc;color: white;"> <img id="roadpart" src="pic/plus.png" height="42" width="42"> tour type </a> <div id="myLinks2"> <a href="city.php">----Per city</a> </div>

Delegate and use classes

I moved the links to not have them move around when the div opens

 document.getElementById("container").addEventListener("click", function(e) { let tgt = e.target; const parent = tgt.closest("a"); if (tgt.tagName === "IMG" && parent && parent.classList.contains("toggle")) tgt = parent; if (tgt.classList.contains("toggle")) { e.preventDefault(); // stop link tgt.classList.toggle("open"); const open = tgt.classList.contains("open") tgt.querySelector("img").src = open? "https://img.icons8.com/flat_round/2x/minus.png": "https://img.icons8.com/flat_round/2x/plus.png"; document.getElementById(tgt.dataset.id).classList.toggle("hide", ;open); } })
 .hide { display: none; }.toggle { background-color: #ccc; color: white; }
 <div id="container"> <a class="toggle" href="#" data-id="myLinks"> <img src="https://img.icons8.com/flat_round/2x/plus.png" height="42" width="42"> travel to </a> <a class="toggle" href="#" data-id="myLinks2"> <img src="https://img.icons8.com/flat_round/2x/plus.png" height="42" width="42"> tour type </a> <div id="myLinks" class="hide"> <a href="athen.php">----Athens</a> </div> <div id="myLinks2" class="hide"> <a href="city.php">----Per city</a> </div> </div>

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