我有這個簡單的HTML和Javascript,它工作得很好。我的問題是,有沒有辦法用循環做到這一點?我可以單獨使用Javascript來切換循環嗎?
我不想使用jQuery - 只需簡單的Javascript,請!
<form action="">
<input type="radio" name="r" onclick="func();" id="r1">
<input type="radio" name="r" onclick="func();" id="r2">
<input type="radio" name="r" onclick="func();" id="r3">
<input type="radio" name="r" onclick="func();" id="r4">
</form>
<div id="sq" style=" width: 100px;
height: 100px;
background: #000;
display: none;"></div>
<div id="ci" style=" width: 100px;
height: 100px;
background: #555;
display: none;></div>
<div id="tr" style=" width: 100px;
height: 100px;
background: #888;
display: none;></div>
<script>
var r1 = document.getElementById("r1");
var r2 = document.getElementById("r2");
var r3 = document.getElementById("r3");
var sq = document.getElementById("sq");
var ci = document.getElementById("ci");
var tr = document.getElementById("tr");
var el = [sq, ci, tr];
var rs = [r1, r2, r3];
function func() {
if(r1.checked) {
sq.style.display = "block";
} else {
sq.style.display = "none";
}
if(r2.checked) {
ci.style.display = "block";
} else {
ci.style.display = "none";
}
if(r3.checked) {
tr.style.display = "block";
} else {
tr.style.display = "none";
}
}
</script>
您可以在codepen here上查看。
感謝的人,這是什麼我在尋找 :) –