正确绑定javascript事件 [英] properly bind javascript events

查看:78
本文介绍了正确绑定javascript事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找绑定javascript事件的最合适有效的方法;特别是onload事件(我希望在页面和所有元素如图像加载之后发生事件)。我知道有很简单的方法可以在jQuery中执行此操作,但我希望更有效的原始javascript 方法。

I am looking for the most proper and efficient way to bind javascript events; particularly the onload event (I would like the event to occur after both the page AND all elements such as images are loaded). I know there are simple ways to do this in jQuery but I would like the more efficient raw javascript method.

推荐答案

有两种不同的方法可以做到这一点。只有一个会起作用;哪一个取决于浏览器。这是一个使用两者的实用方法:

There are two different ways to do it. Only one will work; which one depends on the browser. Here's a utility method that uses both:

function bindEvent(element, type, handler) {
   if(element.addEventListener) {
      element.addEventListener(type, handler, false);
   } else {
      element.attachEvent('on'+type, handler);
   }
}

在您的情况下:

bindEvent(window, 'load', function() {
    // all elements such as images are loaded here
});

这篇关于正确绑定javascript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆