使用单选按钮删除/附加图像



我有一组单选按钮,用于在div中附加和删除图像。我的图像源位于单选按钮内的数据集值中:

<input class="radioGroup" name="radioGroup" type="radio" id="radio1" data-source-image="/image1.jpg" data-source-desc="This is the First Image"> 
<label for="#radio1">Image 1</label><br /> 
<input class="radioGroup" name="radioGroup" type="radio" id="radio2" data-source-image="/image2.jpg" data-source-desc="This is the Second"> 
<label for="#radio2">Image 2</label>

我正在用一个与单选按钮 id 对应的类附加图像,如果未选中,则使用它来删除图像:

 $('.selections input').live("change", function () {
    // 'Getting' data-attributes using dataset 
    var appendImg = $(this).data('sourceImage'); 
    var itemDesc = $(this).data('sourceDesc'); 
    var item = $(this).attr('id');
    if ($(this).is(':radio')) { 
        var radioGroupName = $(this).attr('name');
        var radioGroup = $('input[name="' + radioGroupName + '"]')
        radioGroup.each( function() {
            if ($(this).attr("checked")) {
                $('.imageContainer').append('<img src="' + appendImg + '" alt="' + itemDesc + '" class="' + item + '" />');
            }
            if ( ! $(this).attr("checked")){
                $('.imageContainer').children('img').remove('.' + item);
            }
        });

    } });

不过,我无法让它工作,我已经尝试了此代码的多种变体,每种变体的结果略有不同,但没有一个按预期运行。在使用此代码的情况下,我的第一个单选按钮根本不起作用,第二个单选按钮仅添加其图像。

此外,欢迎任何其他清理它的建议(我的无线电检查在那里,因为我在这个函数中处理其他输入)。

谢谢!

也许你把事情复杂化了...如果将无线电输入包装在标签中,则不需要 id:

<label><input type="radio" .../></label>

然后,与其确定它是否是带有已弃用的live事件的收音机,我认为您也不需要,不如使用这些特定收音机的change事件。如果您有动态无线电输入,那么我建议您在最近的静态容器上使用on,而不是在document上使用live

var $container = $('.imageContainer');
$('input[name=radioGroup]').change(function() {
  var $this = $(this), 
      imgSrc = $this.data('source-image'),
      imgDesc = $this.data('source-desc'),
      $img = $('<img/>', { src: imgSrc, alt: imgDesc });
  $('img', $container).remove(); // remove all images
  $container.append( $img ); // add the image linked to the current input
});

由于无线电是独占的,因此只能选择一个,您无需确定是否选中了它,也无需查找其他图像,除非您在同一容器中已经有图像。在这种情况下,我只会为链接到无线电的图像创建一个额外的包装器。

演示:http://jsbin.com/isitos/1/edit

最新更新