如何使用单选按钮,3个图像和3个状态进行图像交换?

时间:2011-12-14 10:04:13

标签: jquery image radio swap

当点击3个单选按钮中的每个按钮时,我有3个图像需要切换到on state - 并且在未选中时会返回。

足够简单: 与单选按钮关联的值是图像的id和图像的名称(减去状态)。

我希望在单击按钮时与图像src绑定 我如何让它工作?

$(document).ready(function() {

     $(".challengeradio").change(function(){
          if(this.checked){  
             $("#" + this.value +".pic").attr("src").replace("_off", "_on");     
                          }     
                   });     
          });

~~~和请求的XHTML~

 <div id="chooseChallenge">
    <h2> Choose a Challenge </h2>
    <div class="badge" id="weightLossChallenge"> 
    <div class="challengelabel" id="chall_weightloss">
    <input type="radio" value="chall_weightloss" name="challenge" class="challengeradio">
   <strong> the big <br>Thang</strong>
    </div>
    <img border="0" src="http://www.yoozit.net/zone/images/chall_weightloss_on.png" id="chall_weightloss" class="pic"> </div>

    <div class="badge" id="activityChallenge">
     <div class="challengelabel" id="chall_activity">
    <input type="radio" value="chall_activity" name="challenge" class="challengeradio">
    <strong> Activity Tracker<br>Thang</strong>
    </div> <img border="0" src="http://www.yoozit.net/zone/images/chall_activity_off.png" id="chall_activity" class="pic"></div>

    <div class="badge" id="basicChallenge"> 
    <div class="challengelabel" id="chall_basic">
    <input type="radio" value="chall_basic" name="challenge" class="challengeradio">
    <strong>Basic Standard <br>Thang</strong>
    </div>
    <img border="0" src="http://www.yoozit.net/zone/images/chall_basic_off.png" id="chall_basic" class="pic"></div>
  </div>

3 个答案:

答案 0 :(得分:0)

尝试使用$(this).checked,$(this).value

$(".challengeradio").click(function() {
    $("#" + $(this).val() +".pic").attr("src").replace("_off", "_on");   
});

答案 1 :(得分:0)

$("img.addToFavourite").live('click', function() {
    if ($(this).attr("class") == "addToFavourite") {
      this.src = this.src.replace("_off","_on");
      this.title="Remove from favourite"
    } else {
      this.src = this.src.replace("_on","_off");
      this.title="Add to favourite"
    }
    $(this).toggleClass("on");
  });

有两个名为favourite_off.pngfavourite_on.png

的图片

DEMO

答案 2 :(得分:0)

完成!

有点hacky,但做的工作:

http://jsfiddle.net/2Sy2h/26/

代码:

  $(".challengeradio").change(function(){

           if ($(this).prop("checked")) {
          previous = $('img.onlive').first();
          previnput = $('input.onlive').first();

          var preimgsrc = {};
          preimgsrc['src'] = "http://www.yoozit.net/zone/images/"+ previnput.attr('value') + "_off.png" ;
          previous.attr(preimgsrc).removeClass('onlive');
          previnput.removeClass('onlive');
          var imgsrc = {};
          imgsrc['src'] = "http://www.yoozit.net/zone/images/"+ this.value + "_on.png" ;  


          $("#" + this.value +".pic").attr(imgsrc).addClass('onlive');
          $(this).addClass('onlive')   
              }            
            });