append string to image src using js

2020-05-07 09:48发布

问题:

I've got a page where there is <img src="/images/product/whatever-image.jpg" alt="" />

I want it so that upon loading of the page, the string "?Action=thumbnail" is appended to src's value, making it src="/images/product/whatever-image.jpg?Action=thumbnail"

how do I achieve this using js?

回答1:

window.addEventListener('load', function(){
    /* assuming only one img element */
    var image = document.getElementsByTagName('img')[0];

    image.src += '?Action=thumbnail';
}, false);

Note, changing the source of the image will "re-fetch" the image from the server — even if the image is the same. This will be better done on the server-side.


Update after comment:

window.addEventListener('load', function(){
    /* assuming only one div with class "divclassname" and img is first child */
    var image = document.getElementsByClassName('divclassname')[0].firstChild;

    image.src += '?Action=thumbnail';
}, false);    


回答2:

Use this:

window.onload = function() {
    document.getElementById('myImage').src += "/Action=thumbnail";
};