【问题标题】:Replace radio buttons with images using JQuery使用 JQuery 将单选按钮替换为图像
【发布时间】:2011-11-27 03:06:02
【问题描述】:

我有一组单选按钮,我想在选中和取消选中时用图像替换它们。

<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 的帮助。认可您的投入。

【问题讨论】:

  • Alex 和 Yijiang- 我已经看过这个解决方案,但是在图像刻度解决方案中,图像的映射是使用单选按钮的值完成的,这对我没有帮助。实际上问题的格式是这样的,它看起来是重复的,我的错误。我已更新问题并添加了一条注释。
  • 因此我的 可能 重复。很高兴看到您已经对此进行了研究;有时最好链接到您已经阅读过的一些内容,让我们知道哪些内容不能解决您的问题。

标签: jquery image radio


【解决方案1】:

不要重新发明轮子,为此使用一个不错的库:

http://uniformjs.com/

【讨论】:

    【解决方案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');
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多