夺命雷公狗---javascript NO:09 事件绑定的种类1

1)行内绑定

基本语法:

<元素 样式列表 事件=事件的处理程序></元素>

例:

<input type=’button’ value=’点击’ onclick=’display()’ />

例1:定义一个div层,为其赋值一个onclick事件,改变其文字颜色

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<script>
function display(){
document.getElementById(‘result’).style.color=’red';
}
</script>
</head>
<body>
<div id=”result” style=”400px; height:200px; background:blue;” onclick=”display();”>事件编程主要分为三种版定形式,行内绑定,动态绑定,事件监听</div>
</body>
</html>

2)动态绑定

基本语法:

dom对象.事件 = 事件的处理程序

===

document.getElementById(‘id元素’).事件 = 事件的处理程序

例2:改进例1,使其达到结构+样式+行为相分离

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<style type=”text/css”>
div#result{
width:400px;
height:200px;
background:blue;
}
</style>
<script>
window.onload = function(){
document.getElementById(‘result’).onclick = function(){
document.getElementById(‘result’).style.color = ‘red';
}
}
</script>
</head>
<body>
<div id=”result”>事件编程主要分为三种版定形式,行内绑定,动态绑定,事件监听</div>
</body>
</html>

行内绑定与动态绑定中this的指向

行内绑定时,系统的this指针自动指向全局window对象,所以当我们使用this.style.color相当于window.style.color,所以会报错。

注:为什么display函数中的this会指向window对象?

答:我们在全局作用域中所定义的变量或函数都是以属性的形式追加全局window对象中

var i=10;

window.i = 10;

alert(i);相当于alert(window.i);

function display() {

alert(‘hello’);

}

display();相当于window.display();

总结:行内绑定与动态绑定区别

1)行内绑定是写在元素内部的

2)动态绑定是写在script标签中,并通过window.onload进行载入

3)行内绑定中this指向全局window对象

4)动态绑定中this指向当前dom对象

3)事件监听

1)什么是事件监听

所谓的事件监听就是可以为同一对象的同一事件绑定多个事件处理程序

2)如何定义事件监听

IE浏览器:

IE、兼容模式、IE模式

attachEvent(type,callback) :为对象绑定事件监听

参数说明:

type:事件类型,如onclick/onmouseover

callback:事件的处理程序

基本语法:

dom对象.attachEvent(type,callback);

示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<script>
function $(id){
return document.getElementById(id);
}
window.onload = function(){
$(‘btnok’).attachEvent(‘onclick’,function(){
alert(“hello”);
})
$(‘btnok’).attachEvent(‘onclick’,function(){
alert(‘world’);
})
}
</script>
</head>
<body>
<input type=”button” id=”btnok” value=”点击”>
</body>
</html>

W3C浏览器:

火狐、谷歌、Opera、极速

addEventListener(type,callback,capture);

参数说明:

type:事件类型,不带’on’前缀,例click/mouseover

callback:事件的处理程序

capture:浏览器模型,Boolean类型,true:捕获模型,false:冒泡模型,默认false

注:IE浏览器只支持冒泡模型,W3C浏览器支持所有模型

基本语法:

dom对象.addEventListener(type,callback);

示例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset=’utf-8′>
<title></title>
<script>
function $(id){
return document.getElementById(id);
}
window.onload = function(){
$(‘btnok’).addEventListener(‘click’,function(){
alert(“hello”);
})
$(‘btnok’).addEventListener(‘click’,function(){
alert(‘world’);
})
}
</script>
</head>
<body>
<input type=”button” id=”btnok” value=”点击”>
</body>
</html>

总结:IE模型中事件监听与W3C模型中事件监听的区别?

1)定义时语法不同

IE:attachEvent

W3C:addEventListener

2)定义时参数不同

W3C拥有capture参数,代表浏览器模型,IE是没有这个参数的,且IE只支持冒泡模型,W3C同时支持所有模型

3)定义时IE是需要定义on前缀,而W3C是不需要定义on前缀

4)两者在触发顺序上是不同的:

IE:先定义后触发

W3C:先定义先触发

原文地址:https://www.cnblogs.com/leigood/p/5031835.html