我想在不刷新页面的情况下从Web服务器加载图片。 我有简单的页面:
<body><h1>Test</h1>
<div id="mydiv">
<img src="animals.jpg"/>
</div>
</body>
</html>
关键是animals.jpg内容发生了变化(即现在animals.jpg可以是狼的图片但是在分钟之后它会变成猫)然而名称(animal.jpg)停留(服务器覆盖图像内容< em>仅) 所以我想要的是当我点击图片时它将从服务器重新加载它。
到目前为止我做了什么(实际上它是由我发现的几个例子组成的:)):
$(document).ready(function(){
$('#mydiv').click(function(){
//$('#mydiv').load("animals.jpg") // loads text instead of image
//$("#mydiv").append("<img src='animals.jpg'/>"); // appends old picture
//$("#mydiv").html("<img src='animals.jpg'/>") // not responds at all
});
})
不工作,请参阅评论。
虽然我可以加载html:
的 loadme.html :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/></script>
<script type="text/javascript">
$(document).ready(function(){
$('#mydiv').click(function(){
$('#mydiv').load("h1.html")
});
})
</script>
</head>
<body><h1>Test</h1>
<div id="mydiv">
load me!
</div>
</body>
</html>
h1.html :
答案 0 :(得分:1)
您需要更改图片的src
属性才能重新加载。由于src
应该保持不变,所以在它的末尾添加一个随机字符串。这将使浏览器认为它是一个新形象。
$('#mydif>img').attr('src', 'animals.jpg?random=' + Math.random());
答案 1 :(得分:-1)
最容易的方式,对我来说:
<img id="myimg" src="animal.jpg"/>
只需使用Javascript设置src属性:
function f()
{
var img = document.getElementById("myimg");
img.src = "your_new_pic.jpg";
}
当然,如果您需要动画或其他很酷的东西,最好使用JQUERY。