2011-03-29 31 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