我想在未在html DOM中加载图片时更改图片网址。 (在浏览器加载图片之前)
js可以这样做吗?
演示代码:
...
<body>
<img src="old src"> <!-- this **HTML** is loaded from a database and i want to change this src using javascript-->
</body>
....
我试过
$(function(){$(img).attr('src','new src');}); //it is can work ,but the brower will load old image first. then the js will run.
因为从数据库加载 HTML ,我不知道如何在服务器代码(java)中操作html字符串。所以我想用js来改变图像src。
修改
例如:
old src =&#34; old domain / test.jpg&#34;我想将其更改为&#34;右domian2(CDN)/test_width_height.jpg"
旧的src不在服务器中,因此浏览器将首先从服务器获得404错误。 当src更改为新src时,brower将从新src重新加载图像,然后将显示正确的图像。
我首先不想发生错误,我只是希望浏览器从正确的地址加载正确的图像。
答案 0 :(得分:1)
如果您在加载图片时遇到任何问题,可以选择在onError
<img src="old domain/test.jpg" alt="Not Available"
onError="this.src='right domian2(CDN)/test_width_height.jpg';" />
答案 1 :(得分:0)
您可以使用图像完整属性来确定图像是否已加载。如果没有,你可以根据需要修改img标签的src。
请查看以下网址
http://www.w3schools.com/jsref/prop_img_complete.asp
希望这有帮助
答案 2 :(得分:0)
一开始不要在图片标记中添加任何网址。在某些条件下添加它们,如在pageload上
// define the function that assign the image url
function assignImageSrc(){
$('#imageID').prop('src','add your url here');
}
将其称为
<form onload="assignImageSrc()" >
//
</form>
希望它有所帮助...