西风坊

哦,犷野西风,你秋之实体的气息……

« Pro javascript Techniques 读书笔记(二)-js事件机制outline属性 »

Pro javascript Techniques 读书笔记(三)-js事件绑定

为实现无干扰js 的目的,我们需要在html代码以外去注册我们的事件。现在主要有三种绑定方式:

一、传统绑定: 这个说白了其实就是直接将原来写在html代码里的js句柄移到外部文件中。这种做法的优缺点:

a、优点:

1、简单可靠,确保在不同的浏览器中保持一致;

2、处理事件时,this关键字引用的是当前的元素;

b、缺点: 1、只支持冒泡阶段的运行;

2、一个元素一次只能绑定一个事件处理函数,事件处理函数会相互覆盖;

3、事件对象参数只有非IE浏览器可用;

二、符合W3C标准的DOM绑定:

addEventListener函数,它带三个参数(事件名称、处理事件的函数、是否启用捕获的标志) DOM绑定的优缺点:

a、优点: 1、同时支持时间处理的捕获和冒泡阶段,这取决于最后的设置(true时支持捕获);

2、在事件处理函数内部,this关键词引用的是当前元素;

3、事件处理对象总是可以通过处理函数的第一个参数获取;

4、可以为同一个元素绑定你所希望的多个事件而不会相互覆盖;

b、缺点: IE不支持;

例子: 


// Find the first <form> element and attach a ‘submit’ event handler to it
document.getElementsByTagName(“form”)[0].addEventListener(‘click’,function(e){
    // Stop all form submission attempts
    return stopDefault( e );
}, false);

// Attach a keypress event handler to the <body> element of the document
document.body.addEventListener(‘keypress’, myKeyPressHandler, false);

// Attach an load event hanlder to the page
window.addEventListener(‘load’, function(){ … }, false);

 IE的绑定: attachEvent函数 连个参数(on+事件名词、处理事件名)

优缺点: a、优点:

1、可以为同一元素绑定多个事件而不相互覆盖;

b、缺点: 1、仅支持时间捕获的冒泡阶段; 2、this关键词指向了window对象; 3、时间对象仅存在于window.event中; 4、仅IE可用;例子:

b、缺点: IE不支持;

例子: 

 


// Find the first <form> element and attach a ‘submit’ event handler to it
document.getElementsByTagName(“form”)[0].attachEvent(‘onclick’,function(){
    // Stop all form submission attempts
    return stopDefault();
},);

// Attach a keypress event handler to the <body> element of the document
document.body.attachEvent(‘onkeypress’, myKeyPressHandler);

// Attach an load event hanlder to the page
window.attachEvent(‘onload’, function(){ … });
0分/0个投票

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-Blog. Templete from Google黑板报.

浙ICP备08015283号 Copyright 2007 space007.com. Some Rights Reserved.