[英]How to make this functions cleaner?
I don't want to add new lines to the JS code every time I will add a new image to the HTML.我不想每次将新图像添加到 HTML 时都在 JS 代码中添加新行。 But I have no idea how to.但我不知道该怎么做。
$(document).ready(function() {
$('.btn').click(function() {
var bid = $(this).attr('id');
if(bid=="img1" || bid == "img2" || bid == "img3"){
document.getElementById("img1").style.display = "none";
document.getElementById("img2").style.display = "none";
document.getElementById("img3").style.display = "none";
} else {
document.getElementById("img4").style.display = "none";
document.getElementById("img5").style.display = "none";
}
document.getElementById(bid).style.display = "block";
});
});
CSS CSS
.textures {
background: url("images/room.png") center / cover no-repeat;
position: static;
height: 600px;
width: 800px;
}
div>img {
display: none;
position: absolute;
}
[type=radio] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
[type=radio] + img {
cursor: pointer;
height: 60px;
width: 80px
}
[type=radio]:checked + img {
outline: 2px solid #000;
}
HTML. HTML。 Here you can see if I click a radius input from the categories, it will display one of the images from materials.在这里,您可以看到如果我单击类别中的半径输入,它将显示来自材料的图像之一。
<!--Room materials-->
<div class="textures">
<div class="wall">
<img id="img1" src="images/wall/blue.png" />
<img id="img2" src="images/wall/brick.png" />
</div>
<div class="floor">
<img id="img3" src="images/floor/cedro.png" />
<img id="img4" src="images/floor/cipres.png" />
</div>
</div>
<!--Categories-->
<h5>Walls</h5>
<label>
<input type="radio" class="btn" id="img1" name="test" value="small" />
<img src="images/thumbnail/wall/blue.png"/>
</label>
<label>
<input type="radio" class="btn" id="img2" name="test" value="small" />
<img src="images/thumbnail/wall/brick.png"/>
</label>
<h5>Floors</h5>
<label>
<input type="radio" class="btn" id="img3" name="test" value="small" />
<img src="images/thumbnail/floor/cedro.png"/>
</label>
<label>
<input type="radio" class="btn" id="img4" name="test" value="small" />
<img src="images/thumbnail/floor/cipres.png"/>
</label>
First of all, having duplicate IDs in a single document is invalid HTML .首先,在单个文档中有重复的 ID 是无效的 HTML 。 To put data in the HTML indicating a connection to another element, you could use a data attribute instead.要将数据放入 HTML 以指示与另一个元素的连接,您可以改用数据属性。 Extract the data attribute, hide all images, then use the data attribute in a selector:提取数据属性,隐藏所有图像,然后在选择器中使用数据属性:
<input type="radio" class="btn" data-image="img4" name="test" value="small" />
^^^^^^^^^^^^^^^^^
$('.btn').on('change', function() {
const id = $(this).data('image');
$('.textures img').hide();
$('#' + id).show();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.