简体   繁体   中英

Combining jQuery/JavaScript functions

Is there any way to combine all of this to reduce the amount of 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 });

}

Combining methods won't save you space. Take a look at

http://developer.yahoo.com/yui/compressor/

$(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");
        });
    });
});

I don't know exactly what you are trying to do but if possible, you should toggling a class instead of modifying the src attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM