我有一个同样的问题,但我有多个图像URL:如何插入今天的日期到一个图像URL?
我有图像的URL如下:
<img src="https://www.example.com/2023/01/08/dl/01/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/02/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/03/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/04/image.jpg" alt="image"><br>
<img src="https://www.example.com/2023/01/08/dl/05/image.jpg" alt="image"><br>
如何使用javascript在所有IMAGE url上插入今天的日期代码。
这是我能想到的最简短的方法
String(i+1).padStart(2,'0')
将创建01,02等
const yyyymmdd = new Date().toISOString().split('T')[0].split('-').join('/');
document.getElementById('imgContainer').innerHTML = Array.from({length:5}) // generate an array of 5
.map((_,i) => `<img src="https://www.example.com/${yyyymmdd}/dl/${String(i+1).padStart(2,'0')}/image.jpg" alt="image" />`).join(`<br/>`)
<div id="imgContainer"></div>
如果您有超过99张图片,请更改padStart
下面是如何为每个图像添加日期的示例:
const date = new Date();
const dd = String(date.getDate()).padStart(2, '0');
const mm = String(date.getMonth() + 1).padStart(2, '0');
const yyyy = date.getFullYear();
const today = yyyy + '-' + mm + '-' + dd;
const images = document.querySelectorAll('img');
images.forEach(function(img) {
img.src = img.src.replace(/.jpg/, '-' + today + '.jpg');
});
代码如下:
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth() + 1;
month < 10 ? month = '0' + month : month;
let day = date.getDate();
day < 10 ? day = '0' + day : day;
const fullDate = `${year}/${month}/${day}`;
let href = 'https://www.example.com/2023/01/08/dl/05/image.jpg';
var links = document.getElementsByClassName("img");
for(let i = 0; i < links.length; i++) {
links[i].setAttribute("src", `https://www.example.com/${fullDate}/dl/05/image.jpg`);
}
<!-- add a class to all of the images so you can access them with js -->
<!-- you may delete src attr -->
<img alt="image" class="img" ><br>
<img alt="image" class="img"><br>
<img alt="image" class="img"><br>
<img alt="image" class="img"><br>
<img alt="image" class="img"><br>
创建一个函数,将日期添加到单个元素(来自您链接的问题)。使用querySelecterAll()将图像元素放入数组中。
然后像这样做
arrayOfImages.foreach((img) => addDateToImage(img))