2011-03-18 53 views
0

好吧,我有這個迄今爲止,它工作在一定程度上,交換通過多個鏈接網頁上的所有圖片JQuery的

$('a').click(function(e) 
{ 
    e.preventDefault(); 
    var preFix = $(this).attr("href"); 
    $('img.swap').each(
     function() { this.src = this.src.replace('.gif', (preFix)+'.gif'); 
    }); 
}); 

這拉通過「HREF」鏈接,並將其添加到圖像的結尾。問題是,當我點擊第一個鏈接它交換圖像就好了,但第二次點擊圖像中斷的5個鏈接之一。

我猜測它是因爲它只是在第一個末尾添加第二個前綴。我已經嘗試了一些東西,但它只是結束了整個事情。

有兩件事情我需要做的:

1)當你點擊一個鏈接,然後另一個我想刪除舊的前綴和裏邊反新的。

2)如果同一個鏈接被點擊兩次,我需要它首先添加前綴,然後刪除前綴。

非常感謝

+0

幾乎有東西給你的第一個前綴是如何格式化?或者是你可以設置init的東西。 – 2011-03-18 14:36:45

+0

它開始只是banner.jpg,然後當我點擊鏈接時,它會將HREF的內容發送到圖像的末尾,以便banner-bw.jpg。 – 2011-03-18 14:42:25

+0

我在下面修復了我的代碼,以反映您真正需要的內容。我認爲:-D – Neal 2011-03-18 15:11:31

回答

3

試試這個::-D

$('img.swap').each(function{ 
    $(this).data('current_image', this.src); 
    //saves the default image in data 
}) 
$('a').click(function(e){ 
     e.preventDefault(); 
     var preFix = $(this).attr("href"); 
     $('img.swap').each(
     function() { 
     if($(this).data('prefix') != prefix){ 
      this.src = $(this).data('current_image').replace('.gif', (preFix)+'.gif'); 
      $(this).data('prefix', prefix) 
     } 
     else { 
      this.src = $(this).data('current_image'); 
      $(this).data('prefix', '') 
     } 
     }); 
}); 

$(this).data(..)存儲變量在特定的DOM元素,不是做之後,你可以做布爾運算CHACK它反對你的價值:-)

更說明這裏: jQuery.data()

UPDATE

和而不是使用一個(錨)標籤使用一個類名像.changeIMG別的東西:

<span class='changeIMG' postfix='-bw'>Change to black and white</span> 

,並用CSS就可以像一個錨標記:

span.changeIMG { 
    cursor: pointer; 
    color: blue; 
    text-decoration: underline; 
} 

再有就是在上面的代碼2點的變化:

$('a').click(function(e){成爲$('span.changeIMG').click(function(e){
var preFix = $(this).attr("href");成爲var preFix = $(this).attr("postfix");

+0

不幸的是,這不工作,它使一個鏈接點擊,但我會看看jQuery.data()謝謝你。 – 2011-03-18 14:36:01

+0

什麼沒有工作呢? – Neal 2011-03-18 14:36:29

+0

當我點擊鏈接,它只是發送給我的頁面,而不是添加前綴的形象,我只是改變了所有前綴,所以它匹配,但現在仍然運氣 – 2011-03-18 14:39:12

0
$("img.swap").each(function(){ 
    var origSrc = $(this).attr("src"); 
    //original src can now always be accessed 
    $(this).attr("origSrc",origSrc); 
}); 

$("a").click(function(e){ 
    e.preventDefault(); 
    var prefix = $(this).attr("href"); 
    $("img.swap").each(function(){ 
     var origSrc = $(this).attr("origSrc"); 
     var newSrc = origSrc.replace(".gif",prefix+".gif"); 
     $(this).attr("src",newSrc); 
    }); 
}); 
相關問題