jQuery绑定("加载")

Dav*_*rák 6 javascript jquery

var imgLoader = $("<img />");
$(imgLoader).attr("src", "http://localhost/malevil/Content/Images/img_adrenalin.jpg");

$(imgLoader).unbind('load');
$(imgLoader).bind('load', function () {
    alert("event fired");
});
Run Code Online (Sandbox Code Playgroud)

但这项工作仅限于Chrome,问题出在哪里?在IE中,Firefox和Opera加载事件从未被解雇.

Pek*_*ica 12

您需要在设置src属性之前绑定load事件.

作为旁注,您需要了解图像上的加载事件的已知问题:

并且,引用jQuery手册 load():

  • 它不能一致地工作,也不能可靠地跨浏览器
  • 如果图像src设置为与之前相同的src,则它在WebKit中无法正确触发
  • 它没有正确地冒泡DOM树
  • 可以停止为已经存在于浏览器缓存中的图像触发