静态图像的图像onload

Pim*_*ger 8 javascript events

我知道要使onload图像工作,你必须在附加onload处理程序后设置src.但是我想将onload处理程序附加到HTML中静态的图像.现在我用以下方式做到这一点(使用jQquery):

<img id='img1' src='picture.jpg'>
Run Code Online (Sandbox Code Playgroud)

$('#img1').load( function() {
 alert('foo');
})
.attr('src', $('img1').attr('src'));
Run Code Online (Sandbox Code Playgroud)

但这是相当丑陋的并且具有明显的流程,它只能用于仅匹配一个图像的选择器.有没有其他更好的方法来做到这一点?

编辑
我的意思是它只能用于只匹配一个图像的选择器是这样做的:

<img class='img1' src='picture.jpg'>
<img class='img1' src='picture2.jpg'>
Run Code Online (Sandbox Code Playgroud)

$('.img1').load( function() {
 alert('foo');
})
.attr('src', $('.img1').attr('src'));
Run Code Online (Sandbox Code Playgroud)

这两个图像都有src ='picture.jpg'

Bor*_*gar 10

您可以通过调用.trigger()或直接触发事件(或它的处理程序).load().

如果你知道你想要这个事件,因为你知道图像已经加载了,那么你可以这样做:

$('#img1').load(function() {
    alert('foo');
  })
  .trigger('load');  // fires the load event on the image
Run Code Online (Sandbox Code Playgroud)

如果您在文档准备好的情况下运行脚本,或者某些时候尚不清楚图像是否存在,那么我会使用以下内容:

$('img.static')
  .load(function(){
    alert('foo');
    return false; // cancel event bubble
  })
  .each(function(){
    // trigger events for images that have loaded,
    // other images will trigger the event once they load
    if ( this.complete && this.naturalWidth !== 0 ) {
      $( this ).trigger('load');
    }
  });
Run Code Online (Sandbox Code Playgroud)

请注意,如果您没有取消img处理程序中的气泡,则加载事件会冒泡(jQuery 1.3)并且您可能会过早地触发文档上的加载处理程序.

记录:img.src=img.src遗憾的是,触发解决方案无法在Safari上正常运行.您需要将其设置src为其他内容(例如#或about:blank),然后返回以进行重新加载.