绑定事件
2025年4月30日小于 1 分钟
笔记
1.在html标签元素中 属性名='属性值'
<div onclick='func()'></div>
2.使用元素对象的方式
event.onclick = function()
{
alert('iloveyou');
}
3.addEventListener(非IE浏览器 或者在IE9以上使用)
event.addEventListener('click', function(){ })
绑定事件示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件绑定</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
div
{
width:200px;
height:150px;
background:pink;
cursor:pointer;
}
</style>
</head>
<body>
<table border='1' width='900'>
<tr align='center'>
<!-- 绑定事件第一种方式 -->
<td><div id='one' onclick='fun()'>one<div></td>
<!-- 绑定事件第二种方式 -->
<td><div id='two'>two<div></td>
<!-- 绑定事件第三种方式 -->
<td><div id='three'>three<div></td>
</tr>
</table>
<script type="text/javascript">
//绑定事件第一种方式
function fun()
{
alert('这是第一种!');
}
//绑定事件第二种方式
var two=document.getElementById('two');
two.onclick=function()
{
alert('这是第二种!');
}
//绑定事件第三种方式
//监听事件 注意 第三种方式可以多次触发 不同前两种只能触发一次!!!!!!
var three=document.getElementById('three');
three.addEventListener('click',function(){
alert('这是第三种01!');
});
three.addEventListener('click',function(){
alert('这是第三种02!');
});
three.addEventListener('click',function(){
alert('这是第三种03!');
});
</script>
</body>
</html>