简体   繁体   中英

How can i swap one term in img src on all dom images using javascript / JQuery?

I need to swap all img src /products/210x110/foo-bar-foo-front.jpg to /products/210x110/bar-foo-bar-angle.jpg & apply it to every image in the dom.

My current code works but applies the src url from the first image in the dom to all img src attributes:

i need to just replace 1 word...

//toggle image angles
var img = $("div.product-image a img");
$('div#image-angle-switch').toggle(function() {
    $(this).html('<span></span> Angle view ')
    switch_to_low_fi();
}, function() {
    $(this).html('<span></span> Front view')
    img.attr("src", img.attr("src").replace("front", "angle"));
});
$('div#image-angle-switch').click(function() {
    img.attr("src", img.attr("src").replace("toggle"));
});

Could i create an array of each img src, swap one word and reapply to every img?

var tn_array = $("div.product-image a img").map(function() {

    return $(this).attr("src");
});

for (var i=0; i<tn_array.length; i++) {
    console.log(tn_array[i]);
}

Got my array but how should i apply it? Any help much appreciated.

Loop over each image and change it's src.

$('#image-angle-switch').data("view", "front").click(function () {
    var $this = $(this);
    if ($this.data("view") == "front") {
        $this.html('<span></span> Angle view ').data("view","angle");

        // this does the looping
        $("div.product-image a img").attr("src",function (i, src) {
            return src.replace("front", "angle");
        });
    } else {
        $this.html('<span></span> Front view ').data("view", "front");

        // this does the looping
        $("div.product-image a img").attr("src", function (i, src) {
            return src.replace("angle", "front");
        });
    }
});

Also replaced the old depreciated toggle method. Could be made dryer though

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