如果我有一个信标:
<img src="http://example.com/beacon" />
我希望在信标请求完成后调用一个方法。类似于:
<script>
$("img.beacon").load(function() {
// do stuff knowing the beacon is done
});
</script>
有可能吗?是用jQuery写的吗?
发布于 2009-08-10 21:48:52
好的。请记住,需要在src属性之前添加load。
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
如果您已经在标记中定义了图像标记,那么当窗口加载事件被触发时,您将坚持使用,以确保图像已经到达。
发布于 2009-08-10 21:51:18
$('img.beacon').load()
并不总是正确工作,通常我这样做:
$.fn.imageLoad = function(fn){
this.load(fn);
this.each( function() {
if ( this.complete && this.naturalWidth !== 0 ) {
$(this).trigger('load');
}
});
}
上面的代码还涵盖了在执行脚本之前图像已经完成加载的情况。当您在标记中定义图像时,可能会发生这种情况。
像这样使用:
<img src='http://example.com/image.png' class='beacon' />
<script type='text/javascript'>
$(document).ready(function(){ //document.ready not really necessary in this case
$('img.beacon').imageLoad(function(){
//do stuff
});
});
</script>
发布于 2009-08-10 21:55:16
<script type="text/javascript">
$().ready(function() {
$('img#beacon').attr('src', 'http://sstatic.net/so/img/so/logo.png')
.load(function() { alert('Image Loaded'); })
.error(function() { alert('Error Loading Image');
});
});
</script>
这将加载StackOverflow徽标。
如果加载成功,则执行alert('Image Loaded');
。
如果失败,则执行alert('Error Loading Image');
。
当然,这两个函数都可以用您自己的函数替换。作为一个新用户,它拒绝了我的图像标记,但图像标记应该只包含id='beacon'
属性。除非你想添加一个类。我们在这里的代码中设置src
属性,通常您正在监视完成的图像具有以编程方式设置的src
值。
https://stackoverflow.com/questions/1257385
复制相似问题