2011-03-29 61 views
0

有什麼辦法可以將所有這些結合起來以減少javascript的數量?結合jQuery/JavaScript函數

$(document).ready(function() { 

    $(".individualImagebox img").bind("click", function() 
    { 
     var src = $(this).attr("src"); 

     if (src.search(/Red\.jpg$/) >= 0) return; 

     // Removes the red overlay from the images folder 
     $('.individualImagebox img').attr("src", function() { 
      var thisSRC = $(this).attr("src"); 
      return thisSRC.replace(/Red\.jpg$/, ".jpg"); 
     }); 

     // Adds the red overlay from the images folder 
     $(this).attr("src", src.replace(/\.jpg$/, "Red.jpg") ); 
    }); 

}); 

function ShowHide(index) { 

    var itemSelector = ".name:eq(" + index + ")"; 

    $(".name .bio").fadeOut(); 
    $(".name").not(itemSelector).fadeOut(); 

    $(itemSelector).animate({"height": "show"}, { duration: 500 }); 
    $(itemSelector + " .bio").animate({"height": "show"}, { duration: 500 }); 

} 
+0

「.jpg」是一個圖像嗎?如果沒有,爲什麼不刪除src屬性? – bpierre 2011-03-29 15:12:22

+0

.jpg是一個圖像 – 2011-03-29 15:15:03

+0

好吧,我更新了我的答案。 – bpierre 2011-03-29 15:23:33

回答

1
$(function() { // $(function(){}) is a shortcut of $(document).ready(function(){}) 

    var $activeImg; // Maintain a reference to the last activated img 

    $(".individualImagebox img").click(function(){ 
     if (!!$activeImg) { 
      $activeImg.attr("src", function(i, src){ 
       return src.replace(/(.+)Red\.jpg$/, "$1.jpg"); 
      }); 
     } 
     $activeImg = $(this).attr("src", function(i, src){ // replace attribute and updates active img reference 
      return src.replace(/(.+)\.jpg$/, "$1Red.jpg"); 
     }); 
    }); 
}); 

我不知道到底是什麼你正在嘗試做的,但如果可能的話,你應該切換的一類,而不是修改src屬性。

+0

有兩個文件,一個需要「紅色」在他們的最後。例如chuck.jpg和chuckRed.jpg – 2011-03-29 15:25:52

+0

好吧,我更新了代碼。 – bpierre 2011-03-29 15:34:45