2011-09-28 63 views
1

我有一組單選按鈕,當選中或取消選中時,我想用圖像替換它們。使用JQuery替換單選按鈕和圖像

<div id="answerOptions"> 
<input type="radio" name="answeroption" id="r1" value="radio1" checked=''checked'/>radio1<br/> 
<input type="radio" name="answeroption" id="r2" value="radio2"/>radio2<br/> 
</div> 

我有兩個圖像1. button_on.JPG託運單選按鈕和2 button_off.JPG爲未選中單選按鈕。 我想完成以下任務 1.我想用這些圖像替換單選按鈕。 2.在頁面加載時勾選的單選按鈕應該有正確的圖像。

注意:單選按鈕是動態生成的,它們的ID和值在每個請求上都會改變。

我需要使用Jquery的幫助。申請你的投入。

+2

[可能的複製(http://stackoverflow.com/questions/3114166/replacing-radio-buttons-with-different-images),以及[許多有益的通過谷歌的結果(HTTP:/ /www.google.co.uk/search?&q=replace+radio+buttons+image)。 – Alex

+0

Alex和Yi Jiang-我已經看到了這個解決方案,但是在圖像中,解決方案映射的圖像是通過單選按鈕的值完成的。其實問題的格式是這樣的,看起來是重複的,我的錯誤。我已經更新了這個問題並添加了一個註釋。 –

+0

因此,我*可能*重複。很高興看到你已經研究過這個;有時候鏈接到你已經閱讀過的一些東西是很好的,讓我們知道什麼不能解決你的問題。 – Alex

回答

2

下面的代碼做了兩兩件事:1.替代負載的單選按鈕。 2.點擊圖像時更改它們。我不會因爲你的情況而耿耿於懷,但它應該足以讓你開始。

// on load 
$(function() { 
    // replace the checkboxes with the images 
    $("input name='answeroption']").each(function() { 
     if ($(this).attr('checked')) { // radio button is checked onload 
      $(this).hide(); 
      $(this).after($("<img src='button_on.jpg' class='radioButtonImage' />")); 
     } else { // radio button is not checked 
      $(this).hide(); 
      $(this).after($("<img src='button_off.jpg' class='radioButtonImage' />")); 
     } 
    }); 

    // setup click events to change the images 
    $("input.radioButtonImage").click(function() { 
     if($(this).attr('src') == 'button_on.jpg') { // its checked, so uncheck it 
      $(this).attr('src', 'button_off.jpg'); 
      $(this).prev().attr('checked', 'false'); 
     } else { // its not checked, so check it 
      $(this).attr('src', 'button_on.jpg'); 
      $(this).prev().attr('checked', 'true'); 
     } 
    }); 
});