2011-03-18 26 views
0

我必須構建一個具有多種顏色選項的網站,但它也必須能夠提供「縮放」印象。這就是爲什麼我需要頁面上的所有圖像,所以我能夠增加它們的大小。通過一個鏈接在頁面上交換所有圖像JQuery

我唯一的問題是我不知道如何通過一個鏈接添加一個特定的前綴到頁面上的所有圖像。

E.G.點擊粉紅/白色,並將其添加一個前綴_pw所有圖像在頁面上..

任何幫助將是巨大的

+0

前綴添加到所有圖像?改變所有圖像的風格?改變圖像的來源? – Curlas 2011-03-18 12:01:34

+0

是爲圖像本身添加前綴,例如images/banner_pw.jpg – 2011-03-18 12:02:52

回答

1

的其它解決方案公佈至今的工作,但效率極其低下。這裏有一個更好的解決方案:

var isZoom = false; 
$('#some-link').click(function(e) { 
    e.preventDefault(); 
    $('img').each(function() { 
    this.src = isZoom ? this.src.replace('_pw.jpg', '.jpg') : this.src.replace('.jpg', '_pw.jpg'); 
    }); 
    isZoom = !isZoom; 
}); 

這是假設所有的圖像具有相同的.jpg擴展。

或者,你可以使用.attr代替.each

var isZoom = false; 
$('#some-link').click(function(e) { 
    e.preventDefault(); 
    $('img').attr('src', function(i, src) { 
    return isZoom ? src.replace('_pw.jpg', '.jpg') : src.replace('.jpg', '_pw.jpg'); 
    }); 
    isZoom = !isZoom; 
}); 
+1

好短簡單幹淨。 – Loktar 2011-03-18 12:08:30

+0

感謝您的作品完美,但當我再次點擊鏈接時,它會打破圖像,有沒有辦法讓他們點擊它刪除前綴? – 2011-03-18 12:16:23

+0

@John White我已經更新了我的答案,允許切換回來。 – 2011-03-18 12:23:36

0
$('IMG').attr('class','_pw'); 

應該將所有IMG的類別名稱爲「_pw」。

即:

$('#mybutton').click(function(){ 
    $('IMG').attr('class','_pw'); 
}); 
+0

對不起我解釋錯誤,我需要添加前綴到圖像本身E.G. images/banner_pw.jpg – 2011-03-18 12:00:11

+0

'jQuery#onclick'沒有定義,所以你的第二個例子根本不起作用。 – 2011-03-18 14:46:04

0

有可能寫它的一個更簡潔的方式,但它是一個簡單的操作仍然:

$('#pinkButton').click(function() 
{ 
     $('img').each(function() 
     { 
      $(this).attr('src', $(this).attr('src') + '_pw'); 
      // Will take the previous src attribute and add '_pw' in the end. 
     }); 
}); 

有可能需要一些修改上面放後綴在src字符串的右側,但你明白了。 (基本上,確保擴展被移動等)

+0

非常感謝你的工作:) – 2011-03-18 12:11:13

+0

你忘了阻止點擊事件的默認操作。另外,你正在''each'中實例化兩個新的jQuery對象,而不需要任何東西。這是一個巨大的表現。 – 2011-03-18 12:11:52

0
$("img").attr('src', function(i,a) { 
    return a + '_pw'; 
}); 
1
// Get all your zoomable images (maybe with some special class to identify them) 
// Iterate over them 
$('img.specialClass').each(function() { 

    // Get original src attribute 
    var origSrc = this.src; 

    // Split by slash 
    var arraySrc = origSrc.split('/'); 

    // New src attribute is: 
    var newSrc = arraySrc.slice(0,-1).join('/') + // all but last parts of URL 
    '/pw_' + // with a new prefix 
    arraySrc.slice(-1); // and the original file name 

    // Finally, set the new src attribute 
    this.src = newSrc; 
}) 
+1

使用'this.src'而不是'$(this).attr('src')'和'this.src = newSrc'而不是'$(this).attr('src',newSrc)'。 – 2011-03-18 12:13:49

相關問題