简体   繁体   中英

How to alter img src onclick using jQuery or JS

I have multiple images with src URLs that all have

....content/..._gal6.jpg?format=100w

How can I use jQuery or JS to change all URLs to end with

?format=2500w

on click?

Like this

 document.querySelectorAll("img").forEach(img => { const url = new URL(img.src); if (url.searchParams.get("format")) { url.searchParams.set("format", "2500w") console.log(url.toString()) img.src = url.toString() } })
 <img src="bla.jpg?format=250w"> <img src="bla.jpg"> <img src="bla.jpg?format=350w">

Using Javascript:

Change the src property of the image:

function changeImage(){
document.getElementById('test-image').src = "https://url-to-second-image.com/image.png";
}

You can call the function using the click event in the html:

    <img id="test-image" src="the-url/first_image.jpg" onclick="changeImage()">

Here is a jsfiddle: https://jsfiddle.net/f5mwext3/2/

The same way you can change only part of the name (I'm using whole external files for convenience)

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