2

我目前正在使用复选框和单选按钮,根据所选值显示图片。在大多数情况下,我已经能够使一切正常。问题:复选框选择的值显示图像,但未选中时不会删除图片。取消选中复选框时是否可以删除图片?例子

JS

<script>
function check_value(val, id, type) {     
    var el = document.getElementById("imgBox" + id);
    if (val>0 && val<4) { //will trigger when [1,2,3]
         el.src = "images/"+ type + val + ".jpg";    
         el.style.display = "";

  }    
  }      
</script>

HTML

  <h2>Choose a bike</h2>
    <form name="builder">
        <input type="radio" name="field" onclick='check_value(1, 1, "bike")' />KAWASAKI KX 450F
        <br />
        <input type="radio" name="field" onclick='check_value(2, 1, "bike")' />2010 Yamaha Road Star S
        <br />
        <input type="radio" name="field" onclick='check_value(3, 1, "bike")' />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_value(1, 2, "tire")'
        />Michelin Pilot Road 3 Tires
        <br />
        <input type="radio" name="field" value="2" onclick='check_value(2, 2, "tire")'
        />Dunlop Roadsmart Sport-Touring Tires
        <br />
        <input type="radio" name="field" value="3" onclick='check_value(3, 2, "tire")'
        />Pirelli Scorpion Trail Tires
        <br />
    </form>
    <img id="imgBox2" src="#" style="display:none">

  <h2>Choose Accesories</h2>   
    <form name="tire">
        <input type="checkbox" name="field" value="1" onclick='check_value(1, "3a", "accessories")'
        />Chrome Front Plate
        <br />
        <input type="checkbox" name="field" value="2" onclick='check_value(2, "3b", "accessories")'
        />Jacket
        <br />
        <input type="checkbox" name="field" value="3" onclick='check_value(3, "3c", "accessories")'
        />Gloves</form>
    <div id="accessories">
        <img id="imgBox3a" src="#" style="display:none">
        <img id="imgBox3b" src="#" style="display:none">
        <img id="imgBox3c" src="#" style="display:none">
    </div>
4

2 回答 2

2

您必须检查复选框是否被选中。

要添加一个条件来查看复选框是否被选中,您需要在check_value函数中引用该复选框。

所以向函数添加一个额外的参数check_valuesourceElement

function check_value(sourceElement, val, id, type)

调用此函数this

onclick='check_value(this, 1, "3a", "accessories")'

并使用 sourceElement 查看复选框是否被选中:

var el = document.getElementById("imgBox" + id);
if(sourceElement.checked)
{
    //What you are already doing.
}
else
{
    el.src = "";
    el.style.display = "none";
}

示例:http: //jsfiddle.net/nivas/9cKEz/

于 2012-09-08T15:41:32.873 回答
0
<script>
function check_value(el1,val, id, type) {     

    var el = document.getElementById("imgBox" + id);
    if (val>0 && val<4) { //will trigger when [1,2,3]
       if(el1.checked){  el.src = "images/"+ type + val + ".jpg";    
         el.style.display = "";}else{ el.src = "";    
         el.style.display = "none";}

  }   

  }      
</script>

调用函数 onchange check_value(this, 2, "3b", "accessories")

于 2012-09-08T15:47:51.787 回答