![](/img/trans.png)
[英]how to write a javascript variable as source for img tag in html
[英]Send Javascript Variable to HTML Img Source
我正在使用一段 JavaScript 代码更改 WordPress 网站上的图像源(利用 Elementor 编辑器),这是基于单击按钮使用特定字符串更新 URL。 例如,此过程将产生以下结果:
点击前: www.website.com/acoolpage/
点击后: www.website.com/acoolpage/ ?picture=ws10m
这个 HTML 构造函数创建了图像的维度,但在单击按钮后,当 URL 切换到www.website.com/acoolpage/?picture=ws10m
时,不会使用所需的结果更新图像源。 需要哪些额外的步骤和/或编辑? 谢谢!
const urlParams = new URLSearchParams(window.location.search); const pictureParam = urlParams.get('?picture=') const pictureUrl = switch (pictureParam) { case 'ws10m': return 'https://www.website.com/graphics/image_ws10m.png' break default: return 'https://www.website.com/graphics/image_t2m.png' break }
<body> <img src=pictureURL alt="Test" width="1920" height="1080"> </body>
img src=pictureURL
是一厢情愿的想法switch 语句评估表达式,将表达式的值与 case 子句匹配,并执行与该 case 关联的语句,以及匹配 case 之后的 case 中的语句。
你可能打算这样做
window.addEventListener("DOMContentLoaded", function() { const urlParams = new URLSearchParams(window.location.search); const pictureParam = urlParams.get('picture') document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam === 'ws10m'? 'ws10m.png': 't2m.png'}` })
<img src="" id="img" alt="Test" width="1920" height="1080">
更多版本的替代品
window.addEventListener("DOMContentLoaded", function() { const urlParams = new URLSearchParams(window.location.search); const pictureParam = urlParams.get('picture'); document.getElementById("img").src = `https://www.website.com/graphics/image_${pictureParam? pictureParam: 'default.png'}` })
<img src="" id="img" alt="Test" width="1920" height="1080">
您可以使用locationchange
事件来检测 URL 是否已通过单击按钮进行更改。
代码如下:
const obj = document.getElementById('#IDFromDOM');
function updateImage(){
const urlParams = new URLSearchParams(window.location.search);
const pictureParam = urlParams.get('picture')
const pictureUrl = pictureParam === 'ws10m' ? 'https://www.website.com/graphics/image_ws10m.png' : 'https://www.website.com/graphics/image_t2m.png'
obj.src = pictureUrl;
}
window.addEventListener('locationchange', updateImage);
updateImage(); //Fire a first time on page load
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.