当我按下按钮时,我想切换多个图像。 例如,如果我按下名为“ a”的按钮,则要显示名为“ a'”的图像。
答案 0 :(得分:0)
您可以执行以下操作来在单击另一个元素时切换元素
let clickable = document.getElementsByClassName("click")
let togglable = document.getElementsByClassName("toggle")
function hideAllToggleable() {
// for each togglable hide it
for (let toggle of togglable) {
toggle.style.display = "none"
}
}
// hide them by default
hideAllToggleable()
// on each clickable
for (let click of clickable) {
// add an event on click
click.addEventListener('click', e => {
let visible = document.getElementById("t" + e.target.dataset.show).style.display === 'block'
// hide everything
hideAllToggleable()
if (! visible) {
// show the one we want to show
document.getElementById("t" + e.target.dataset.show).style.display = "block"
}
})
}
<div class="click" data-show="1">click me to show 1</div>
<div class="click" data-show="2">click me to show 2</div>
<div class="click" data-show="3">click me to show 3</div>
<div class="click" data-show="4">click me to show 4</div>
<div class="click" data-show="5">click me to show 5</div>
<div class="toggle" id="t1">1</div>
<div class="toggle" id="t2">2</div>
<div class="toggle" id="t3">3</div>
<div class="toggle" id="t4">4</div>
<div class="toggle" id="t5">5</div>
我使用了datasets
这个自定义属性,可以在元素上存储数据时使用它
答案 1 :(得分:0)
使用querySelectorAll循环
document.querySelectorAll("[id^=tf1]").forEach(function() { // any button
this.addEventListener("click",function() {
var id = this.id.substring(1).replace("-","_");
document.querySelectorAll("[id^=f1]").forEach(function() { // all elements
this.style.display="none";
});
document.getElementById(id).style.display="none"?"block":"none"; // toggle the specific element
});
});
答案 2 :(得分:0)
我建议您创建一个全局变量来标记所选的图像
let chosenImage;
document.querySelectorAll("[id^=tf1]").forEach(function() {
click.addEventListener('click', e => {
if(chosenImage != null){
chosenImage.display = 'none'
}
this.display = this.display === 'block'? 'none' :'block'
}
}