JavaScript Tip: Add a random number (or millisecond time) to all links on the page
P粉704196697
P粉704196697 2024-01-16 20:01:56
0
1
394

I have a static HTML page with the address https://MyPage/index.html

The

page contains several images located at https://MyPage/MyImages

The link to the image in the HTML source code is as follows:

When the button is clicked or better yet the page loads, all image links should be rewritten by adding a random number or e.g. the current time in milliseconds, so that the link looks like this:

I believe a possible starting point can be found here:

Change all links on the page

How to change all links using javascript

How do I change every link on the page to new content?

From there, how do I add (instead of a constant redirect) to the example given so that a random number or millisecond time is appended to all image links?

P粉704196697
P粉704196697

reply all(1)
P粉594941301

const time_to_img = () => {
  document.querySelectorAll('img').forEach(e => {
    const dateStr = Date.now();
    const date = new Date(dateStr);
    e.src = e.src + '?' + date.getTime();
  })
}
window.addEventListener('load', time_to_img);
<img src="https://picsum.photos/id/1/300/200" alt="">
<img src="https://picsum.photos/id/7/300/200" alt="">
<img src="https://picsum.photos/id/12/300/200" alt="">
<img src="https://picsum.photos/id/22/300/200" alt="">

In the loop, you calculated the time in milliseconds and then added it to the src of each image?

Now, if you want to use different numbers for each image, you need to add something (random numbers?). Here, for 4 images, all operations are completed within the same millisecond.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!