簡體   English   中英

重新加載 web 頁面不會更新 img.src

[英]Reloading the web page does not update img.src

我最近開始學習 HTML 和 JS 並在這一點上卡住了。 我正在使用“cataas”更新新圖像,但每次重新加載頁面時,都沒有任何變化。

 function loadCatPicture() { var img = document.getElementById('cat-picture'); img.src = 'https://cataas.com/cat'; }; window.onload = function() { loadCatPicture(); };
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1,0"> <title>Document</title> </head> <body> <h1>Cats Sleep Anywhere</h1> <p> Cats sleep anywhere, any table. any chair,<br> Top of piano, window-ledge, in the middle. on the edge,<br> Open draw, empty shoe. anybody's lap will do,<br> Fitted in a cardboard box. in the cupboard with your frocks.<br> Anywhere! They don't care! Cats sleep anywhere.<br> <br> <img id="cat-picture"> <b>Eleanor Farjeon</b></p> <p></p> </body> </html>

您的瀏覽器可能只是緩存來自cataas.com的圖像響應。

根據這個 SO question的答案,您可以在請求 URL 中添加一些無害的GET參數,這些參數將被服務器忽略,但最終會欺騙您的瀏覽器不緩存響應:

 function loadCatPicture() { var img = document.getElementById('cat-picture'); img.src = 'https://cataas.com/cat?ver=' + (new Date().getTime()); }; window.onload = function() { loadCatPicture(); };
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1,0"> <title>Document</title> </head> <body> <h1>Cats Sleep Anywhere</h1> <p> Cats sleep anywhere, any table. any chair,<br> Top of piano, window-ledge, in the middle. on the edge,<br> Open draw, empty shoe. anybody's lap will do,<br> Fitted in a cardboard box. in the cupboard with your frocks.<br> Anywhere! They don't care! Cats sleep anywhere.<br> <br> <img id="cat-picture"> <b>Eleanor Farjeon</b></p> <p></p> </body> </html>

您的瀏覽器可能正在緩存圖像。 由於圖像 URL 實際上並沒有改變,而只是實際圖像。 要查看代碼的更改,您必須清除瀏覽器的緩存。 在 Chrome 中,它就像清除您的歷史記錄一樣簡單;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM