2012-11-11 66 views
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); 
      } 

     }); 


    } }); 

雖然我不能得到這個工作,但我已經嘗試了多種此代碼的變體,每個變體的結果稍有不同,但都不像預期的那樣運行。在這個代碼的情況下,我的第一個單選按鈕根本不起作用,而第二個單選按鈕只添加它的圖像。

此外,任何其他建議清理它將是受歡迎的(我的無線電檢查存在,因爲有我在這個功能處理其他輸入)。

謝謝!

回答

1

也許你事情複雜...如果你包裹在標籤的無線電輸入你不需要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

+0

感謝elclanrs,這絕對是對我來說是正確的方向邁出的一步。我應該詳細闡述一下,因爲我需要考慮不同數量的無線電輸入組,並且無法清除容器中的所有圖像,因爲我通過其他複選框顯示了其他圖像。另外,我知道在標籤中包裝輸入是有效的,但我通常寧願將它們分開。 –

+1

然後,您可以使用您正在使用的課程,應該這樣做,並將所需的所有組添加到更改事件中。 http://jsbin.com/isitos/2/edit < - 演示似乎很奇怪,因爲圖像重複,但它的作品。 – elclanrs

+0

完美!非常感謝你的幫助。 –