我目前正在根据从单选按钮中选择的值显示图像。但是我目前正在使代码尽可能简短和高效。我有几个类别可供选择,我处理这个问题的方式需要我写几个check_value#
。有没有办法将这两个功能结合起来?所以将来如果我有 5 或 7 个类别,我将不必为每个类别设置一个功能。例子
<script>
function check_value(val) {
var el = document.getElementById("imgBox1");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/bike" + val + ".jpg";
el.style.display = "";
}
}
function check_value1(val) {
var el = document.getElementById("imgBox2");
var img = imgs[val];
if (val>0 && val<4) { //will trigger when [1,2,3]
el.src = "images/tire" + val + ".jpg";
el.style.display = "";
}
}
</script>
HTML
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" value="1" onclick='check_value(0)'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" value="2" onclick='check_value(1)'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" value="3" onclick='check_value(2)'/> Aprilia RSV4<br />
</form>
<img id="imgBox1" src="#" style="display:none">
<h2>Choose a tire</h2>
<form name="tire">
<input type="radio" name="field" value="1" onclick='check_value1(0)'/> Michelin Pilot Road 3 Tires<br />
<input type="radio" name="field" value="2" onclick='check_value1(1)'/> Dunlop Roadsmart Sport-Touring Tires<br />
<input type="radio" name="field" value="3" onclick='check_value1(2)'/> Pirelli Scorpion Trail Tires<br />
</form>
<img id="imgBox2" src="#" style="display:none">