0

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);
            }

        });


    } });

これを機能させることはできませんが、このコードの複数のバリエーションを試しましたが、それぞれわずかに異なる結果が得られましたが、期待どおりに機能するものはありませんでした。このコードの場合、最初のラジオボタンはまったく機能せず、2番目のラジオボタンはその画像を追加するだけです。

また、それをクリーンアップするための他の提案も歓迎されます(この関数で処理している他の入力があるため、私のラジオチェックがあります)。

ありがとう!

4

1 に答える 1

1

多分あなたは物事を複雑にしているでしょう...あなたがラベルでラジオ入力を包むならば、あなたはIDを必要としません:

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

次に、非推奨のイベントが含まれているラジオであるかどうかを判断する代わりに、liveどちらも必要ないと思いますがchange、それらの特定のラジオのイベントを使用できます。動的な無線入力がある場合はon、ではなく、最も近い静的コンテナで使用することをお勧めliveしますdocument

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

});

ラジオは専用であるため、1つしか選択できません。同じコンテナ内にすでに画像がない限り、チェックされているかどうかを確認したり、他の画像を検索したりする必要はありません。その場合、ラジオにリンクされている画像のラッパーを追加するだけです。

デモ: http: //jsbin.com/isitos/1/edit

于 2012-11-11T21:51:21.383 に答える