彷佛是Jquery的一个Bug,由于通常来讲,在任何状况下都不该该重复触发onload事件。html
重现Bug的代码以下:jquery
$(function(){ $("#test").append('<img onload="alert(\'hi\')" src="Image.jpg">'); })
百般百度无果,最终在StackOverFlow上找到了一样的问题:app
http://stackoverflow.com/questions/10816053/jquery-img-added-through-append-triggers-onload-twicehtm
该问题中给出的回答是Jquery在create和shift元素的时候都会致使触发onload事件。听上去并非很科学。不过至少给出了一种能够避免Bug的写法:事件
$(function() { $("#test").append( $("<img>").attr({ src: "Bachalpseeflowers.jpg", onload: "alert(\'hi\')" }) ); });
或者,能够使用$('#test').html()方法代替append方法添加包含onload事件的图片。图片