Javascript,切换具有相同名称的单选按钮图像

时间:2014-12-01 16:48:49

标签: javascript jquery html radio-button

我有一个表单,我用图像替换了单选按钮,当单击图像时,它们显示图像的较暗形式以显示它是活动的,但是,我无法弄清楚当我点击不同的单选按钮图像时,如何让较暗的图像返回到标准图像。这是我到目前为止所做的。



$("[name=make]").on({
  "click": function() {
    var val = $(this).attr('value');
    console.log("Value: " + val);
    var imgName = "#" + val + "-icon";
    $(imgName).attr('src', '/images/make-icons/' + val + '-hover.png');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input id="ford" class="dis-none" type="radio" name="make" value="ford">
  <img class="make-icons" src="/images/make-icons/ford.png" id="ford-icon">
</label>
<label>
  <input id="chevrolet" class="dis-none" type="radio" name="make" value="chevrolet">
  <img class="make-icons" src="/images/make-icons/chevrolet.png" id="chevrolet-icon">
</label>
<label>
  <input id="gmc" class="dis-none" type="radio" name="make" value="gmc">
  <img class="make-icons" src="/images/make-icons/gmc.png" id="gmc-icon">
</label>
<label>
  <input id="dodge" class="dis-none" type="radio" name="make" value="dodge">
  <img class="make-icons" src="/images/make-icons/dodge.png" id="dodge-icon">
</label>
<label>
  <input id="toyota" class="dis-none" type="radio" name="make" value="toyota">
  <img class="make-icons" src="/images/make-icons/toyota.png" id="toyota-icon">
</label>
<label>
  <input id="nissan" class="dis-none" type="radio" name="make" value="nissan">
  <img class="make-icons" src="/images/make-icons/nissan.png" id="nissan-icon">
</label>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

检查收音机的状态

$("[name=make]").on({
  "change": function() {
    var suffix = '';
    if ($(this).is(':checked')) {
        suffix = '-hover';
    }
    var val = $(this).attr('value');
    console.log("Value: " + val);
    var imgName = "#" + val + "-icon";
    $(imgName).attr('src', '/images/make-icons/' + val + suffix + '.png');
  }
});