WEB开发网
开发学院网页设计JavaScript JavaScript事件监听完整实例(含注释) 阅读

JavaScript事件监听完整实例(含注释)

 2010-09-14 13:19:36 来源:WEB开发网   
核心提示:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmln

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript事件监听完整实例(含注释)</title>
<meta name="generator" content="editplus" />
<meta name="Keywords" content="AddEventHandler,addEventListener,attachEvent,appendChild,getElementsByTagNamem,createElement,createTextNode,IE与FF兼容性,JavaScript事件,JavaScript监听">
<script type="text/javascript">...
var oEventUtil = new Object();
oEventUtil.AddEventHandler = function(oTarget,sEventType,fnHandler)
...{
//IE和FF的兼容性处理
//如果是FF
if(oTarget.addEventListener)...{
oTarget.addEventListener(sEventType,fnHandler,false);
}
//如果是IE
else if(oTarget.attachEvent)...{
oTarget.attachEvent('on'+sEventType,fnHandler);
} else...{
oTarget['on'+sEventType] = fnHandler;
}
};
//定义oT事件函数
var oT = function()
...{
var oEvent = arguments[0];
var oTarget = oEvent.target || oEvent.srcElement;
alert(oTarget.tagName+' '+oTarget.innerHTML+' '+oEvent.type);
}
//页面加载时制造36个p,每个p里面显示的文字是Line + i
window.onload = function()...{
for(var i = 0;i<36;i++)
...{
var oP = document.createElement('p');
var oText = document.createTextNode('Line'+i);
oP.appendChild(oText);
//在文档的第一个div里面添加这些p
document.getElementsByTagName('div')[0].appendChild(oP);
}
//找到所有的p,并添加click的事件监听
var oPList = document.getElementsByTagName('p');
for(var i = 0;i<oPList.length;i++)
...{
oEventUtil.AddEventHandler(oPList[i],'click',oT);
}
}
</script>
<style type="text/css">...
*
{...}{
margin:0px;
padding:0px;
}
div
{...}{
margin:10px auto;
width:690px;
border:solid 1px #000;
min-height:600px;
padding:20px;
}
div p
{...}{
padding:4px;
margin-left:4px;
margin-top:4px;
border:solid 1px blue;
width:100px;
float:left;
}
pre{...}{
margin:20px 0 0 0;
}
a
{...}{
text-indent:4em;
}
</style>
</head>
<body >
<pre>
       代码来源网络。

JutinYoung稍作整理并注释,更多相关文章请访问:

</pre>
<a href="http://justinyoung.cnblogs.com" target="_blank">http://justinyoung.cnblogs.com</a>
<div>
</div>
</body>
</html>

Tags:JavaScript 事件 监听

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接