[DOM Event Learning] Section 1 DOM Event 处理器绑定的几种方法

[DOM Event Learning] Section 1 DOM Event处理器绑定的几种方法

 
  网页中经常需要处理各种事件,通常的做法是绑定listener对事件进行监听,当事件发生后进行一些特定处理.
  监听事件的几种方法如下文.
 

第一种,写在页面标签里面

<button onclick="alert('Hello')">Say hello</button>

  上面这行代码,将按钮点击后的弹窗操作在标签声明的时候就绑定了.

  这是一种糟糕的方法,原因如下:
  1.View code(HTML)和交互code(JS)强耦合了.这意味着每次我们想改方法,都需要编辑HTML.
  2.可扩展性差.如果这个方法需要被附加在多个元素上,重复的代码会让页面膨胀,并且维护困难.
 
 

第二种,用JavaScript设置元素对应的onXXX事件属性

  如代码:
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        window.onload = function () {
            // Event binding using onXXX property from JavaScript
            var helloBtn = document.getElementById("helloBtn");
            helloBtn.onclick = function (event) {
                alert("Hello Button");
            }
        }
    </script>

</head>
<body>
<button id="helloBtn">Say hello</button>
</body>
</html>
  这种方法比较简单,并且会覆盖之前的handler,也没有什么浏览器兼容的问题.
 
 

第三种,使用addEventListener()方法

  获取元素之后,可以用addEventListener()方法:
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript">
        window.onload = function () {
            // Event binding using addEventListener
            var helloBtn = document.getElementById("helloBtn");
            helloBtn.addEventListener("click", function (event) {
                alert("Hello.");
            }, false);

        }
    </script>
</head>
<body>
<button id="helloBtn">Say hello</button>
</body>

</html>
  这种方法在现代的浏览器上是工作良好的,但是在IE9之前的IE浏览器是没有这个方法的,它们用attachEvent().
 

第四种,使用jQuery的方法进行事件处理器绑定

  jQuery为我们处理了这种不兼容问题,因此可以用jQuery的方法来绑定事件:
// Event binding using a convenience method
$("#helloBtn").click(function (event) {
    alert("Hello.");
});

 

  jQuery监听事件有很多种方法:
// The many ways to bind events with jQuery
// Attach an event handler directly to the button using jQuery's
// shorthand `click` method.
$("#helloBtn").click(function (event) {
    alert("Hello.");
});

// Attach an event handler directly to the button using jQuery's
// `bind` method, passing it an event string of `click`
$("#helloBtn").bind("click", function (event) {
    alert("Hello.");
});

// As of jQuery 1.7, attach an event handler directly to the button
// using jQuery's `on` method.
$("#helloBtn").on("click", function (event) {
    alert("Hello.");
});

// As of jQuery 1.7, attach an event handler to the `body` element that
// is listening for clicks, and will respond whenever *any* button is
// clicked on the page.
$("body").on({
    click: function (event) {
        alert("Hello.");
    }
}, "button");

// An alternative to the previous example, using slightly different syntax.
$("body").on("click", "button", function (event) {
    alert("Hello.");
});
 
  jQuery 1.7开始,所有的事件绑定方法最后都是调用.on()方法.
  上面这个例子中,前三个方法调用是等价的.
  第四个和第五个方法,监听的是body上所有button元素的click事件.
  DOM树里更高层的一个元素监听发生在它的children元素上的事件,这个过程叫做事件代理(event delegation).
 
 

参考资料

posted @ 2015-03-20 18:18  圣骑士wind  阅读(1269)  评论(0编辑  收藏  举报