我試圖為img我的 HTML 檔案中的元素創建一個 src ,但由于某種原因,當我嘗試將源插入影像時,作業區無法將該img物件識別為影像物件,因此不允許src 要插入那里。
需要強調的是,這個問題只存在于我作業的作業環境(WebStorm)中。當我嘗試將代碼放入在線作業環境時,效果很好。
盡管有這樣的問題,我還是嘗試將 src 放入 WebStorm:
HTML:
<img id="img" src="https://source.unsplash.com/random">
JS:
let img = document.getElementById("img");
img.src = "https:\/\/images.dog.ceo\/breeds\/terrier-toy\/n02087046_3843.jpg";
但它只是讓作業環境對這個錯誤做出反應:
Cannot set properties of null (setting 'src')
uj5u.com熱心網友回復:
正如問題中所寫,有 2 (no, 3) 個選項可以修復錯誤。
選項 1:普通字串參考
img.src = "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg";
選項 2:在原始轉義字串周圍添加引號
img.src = "https:\/\/images.dog.ceo\/breeds\/terrier-toy\/n02087046_3843.jpg";
選項 3:設定屬性
img.setAttribute("src", "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg");
uj5u.com熱心網友回復:
看看這個代碼。我添加setTimeout了 2 秒只是為了可視化。你可以setTimeout從這里洗掉你的情況。
function changeImage() {
setTimeout(function(){
var image = document.getElementById("img")
image.src = "https://i.imgur.com/xNE8K6Q.jpeg"
}, 2000)
}
changeImage()
<html>
<body>
<img id="img" src="https://i.imgur.com/hk1iahZ.jpeg" height="100" width="100" />
</body>
</html>
uj5u.com熱心網友回復:
標簽的屬性總是有字串值,所以把你的url作為字串。根據您的代碼,您可以嘗試此操作或更新您的代碼并更詳細地描述問題
let img = document.getElementById("img");
img.src = "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg";
<img id="img" src="https://source.unsplash.com/random">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344967.html
標籤:javascript html
下一篇:使用jquery腳本追加元素
