我正在使用一段 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>
uj5u.com熱心網友回復:
- 獲取錯誤的電話
- 圖片來源沒有分配到任何地方,
img src=pictureURL是一廂情愿 - 開關不回傳值
switch 陳述句計算運算式,將運算式的值與 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">
uj5u.com熱心網友回復:
您可以使用該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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451300.html
標籤:javascript html 图片 元素
