2014-07-01 72 views
0

Sub.html改變圖像源的最佳方式:如何編寫使用條件的Jquery

<div> 

<img src ="worlds/application/images/aa.png" class="path"/> 
<img src ="worlds/application/images/bb.png" class="path"/> 
<img src ="worlds/application/images/cc.png" class="path"/> 
<img src ="worlds/application/images/dd.png" class="path"/> 
<img src ="worlds/application/images/ee.png" class="path"/> 

</div> 

的Jquery:

$('#main').load("../sub.html",function(data){ 
        var imgSrc = $('.path'); 
        var img1 = imgSrc[0].src.split('application')[0]+"css/images/aa.png"; 
        var img2 = imgSrc[1].src.split('application')[0]+"css/images/bb.png"; 
        var img3 = imgSrc[2].src.split('application')[0]+"css/images/cc.png"; 
        var img4 = imgSrc[3].src.split('application')[0]+"css/images/dd.png"; 
        var img5 = imgSrc[4].src.split('application')[0]+"css/images/ee.png"; 
       if(imgSrc[0].src.indexOf('aa')>-1){ 
        imgSrc[0].attr('src',img1); 
       } 
       }); 

是否有改變所有圖像的路徑中的任何最好的方法。我已經厭倦了,因爲我需要在應用程序級別追加我的新url,所以我正在分割路徑直到應用程序節點。

回答

2

這是做你所做的事情的另一種方式。在此代碼中,您可以擁有任意數量的圖像,只需要將它們的path作爲CSS類。

$('#main').load("../sub.html",function(data){ 
    var newPath = 'http://localhost:8080/Content/css/images/'; 
    $.each($('.path'), function(index){ 
    var originalSource = $(this).attr('src'); 

    // Replacing the source 
    var newSource = newPath + originalSource.substr(originalSource.lastIndexOf('/') + 1); 

    // Setting the new value of src 
    $(this).attr('src', newSource); 
}); 
}); 

您可以點擊這裏工作的例子:http://jsfiddle.net/7zs7N/

希望它能幫助!

+0

感謝ü非常它就像一個魅力,我需要幫助:我的完整的URL將是這樣的:HTTP://本地主機:8080/ABC/DEF/GHI/JKL /Content/css/images/aa.png ...你有什麼代碼給出的工作正常,但路徑給出了錯誤,我需要從路徑中刪除ghi和jkl,那麼它將適用於我如何刪除從url – user1853128

+1

我更新了我的答案,以符合您的評論中的requeriment。但是,我建議您使用相對URL而不是絕對URL,它使您的文件更具可移植性。 – EmCo

+0

非常感謝你的兄弟....已經使用window.location.href而不是採取http:// localhost – user1853128

1

嘗試像

$(".class > img").each(function() { 
    var src = $(this).attr('src');   
    $(this).attr('src', 'newsrc');   
}); 
+0

使用id而不是class(包含所有imgtags的div的id)。即$(「#ID> img」)。each(function(){}); – cracker