javascript - 浏览器扩展仅替换为 1img
问题描述
我的扩展程序应该用来自单一来源的 gif 替换页面上的所有图像(每次单击时生成不同的 gif)。但是当迭代页面图像时,会将它们全部替换为相同的 gif。我可以看到浏览器只加载一次并在任何地方替换它,我该如何避免呢?
console.log("Fear me!");
let imgs=document.getElementsByTagName('img');
for(elt of imgs){
elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif';
}
解决方案
一种常用的解决方案是在 URL 的末尾添加一个唯一的时间戳,这样它就不会被缓存。在这里,我只要求提供一次时间戳,然后为每张图片添加 +1。
(请原谅 HTML 中的 inline 突兀的 JS 函数,仅用于示例)
function refresh1(){
let imgs=document.getElementsByTagName('img');
for(elt of imgs){
elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif';
}
}
function refresh2(){
let imgs=document.getElementsByTagName('img');
let time=(new Date()).getTime();
for(elt of imgs){
elt.src='https://api.thecatapi.com/api/images/get?format=src&type=gif&t=' + time;
time++;
}
}
img {
width: 200px;
}
<button onclick="refresh1()">without timestamp</button>
<button onclick="refresh2()">with timestamp</button><br>
<img src=""/>
<img src=""/>
推荐阅读
- asp.net-core - ASP-NET.core如何实现资源文件本地化?
- sql - SQL查询根据列分组获取总人数
- python - python Rock Paper Scissors项目中的函数调用问题
- azure - 如何在 azure ad 多租户 dotnet Web 应用程序中获取角色?
- html - 在 HTML CSS 中的图像上添加文本
- javascript - 如何在尚未渲染的元素中应用 css 类?
- jquery - 构建嵌套数组Jquery
- vue.js - Facebook 调试器未抓取 Nuxt 元标记
- python - 如何从 django ORM 中的连接表中获取列
- c# - 在对 Generic 的调用中传递对象的类型