通过Jquery append方法添加的img元素被执行了两次onload事件

似乎是Jquery的一个Bug,因为一般来说,在任何情况下都不应该重复触发onload事件。

重现Bug的代码如下:

$(function(){ 
    $("#test").append('<img onload="alert(\'hi\')" src="Image.jpg">');
})

百般百度无果,最终在StackOverFlow上找到了同样的问题:

http://stackoverflow.com/questions/10816053/jquery-img-added-through-append-triggers-onload-twice

该问题中给出的回答是Jquery在create和shift元素的时候都会导致触发onload事件。听上去并不是很科学。不过至少给出了一种可以避免Bug的写法:

$(function() {
    $("#test").append(
        $("<img>").attr({
            src: "Bachalpseeflowers.jpg",
            onload: "alert(\'hi\')"
        })
    );
});

或者,可以使用$('#test').html()方法代替append方法添加包含onload事件的图片。

posted @ 2015-01-27 15:38  justlancer  阅读(2568)  评论(0编辑  收藏  举报