2013-04-02 78 views
0

我想用我的圖像製作單選按鈕。所以我定義我的div像這樣:jQuery與兄弟姐妹切換img

<div id="LabBox"> 
    <img class="dlike" alt="dlike" src="images/dlike_OFF.png"/> 
    <img class="check" alt="check" src="images/check_OFF.png"/> 
    <img class="funny" alt="funny" src="images/funny_OFF.png"/> 
    <img class="idea" alt="idea" src="images/idea_OFF.png"/> 
    <img class="imp" alt="imp" src="images/imp_OFF.png"/> 

</div> 

我想在文件名進行切換。所以我用後續jqueqy代碼:

$("#LabBox img").click(function() { 

var src;  
var srcname = $(this).attr("src"); 


    // turn on! 
if(srcname.toLowerCase().indexOf("off") >= 0){ 

    //(e.g images/dlike_OFF.png -> images/dlike_ON.png) 
src = $(this).attr("src").replace("OFF", "ON"); 
    $(this).attr("src", src); 
} 
    // All others turn off! for other words src swap. 
    var src2 =$(this).siblings().attr("src").replace("ON", "OFF"); 
    // All images are the same pic. why?? ---> src="images/dlike_OFF.png" 
    console.log(src2); 
    $("#LabBox img").attr("src",src2); 

    }); 

的問題是,當我想更換我的選擇的標籤(圖像)。所有IMG改變同IMG這是「圖像/ dlike_OFF的所有「兄弟」。 png「(第一個)。 我該如何改變我的所有img使用兄弟姐妹()?或者我如何適應我的腳本交換所有圖像?

回答

1
$("#LabBox img").click(function() { 
    if (this.src.indexOf('OFF') != -1) { 
     this.src = this.src.replace('OFF', 'ON'); 
    } 
    $(this).siblings().attr('src', function(i,src) { 
     return src.replace('ON', 'OFF') 
    }); 
}); 
1

LIVE DEMO

$("#labBox").on('click','img[src$=OFF]',function() { 
    this.src = this.src.replace('OFF', 'ON'); 
    $(this).siblings().each(function(){ 
    this.src = this.src.replace('ON', 'OFF'); 
    }); 
});