<html>
<head>
<meta charset="utf-8"/>
<title>遍历onclick</title>
<script>
window.οnlοad=function(){
oBtn=document.getElementsByTagName("input");
for(var i=0;i<oBtn.length;i++){
oBtn[i].index=i;
oBtn[i].οnclick=function(){
alert(this.index);
}
}
}
</script>
</head>
<body>
<input type="button" value="button1" /><input type="button" value="button1" /><input type="button" value="button1" /><input type="button" value="button1" />
</body>
<html>
原理:通过for循环获取每个元素,给每个元素添加事件。
关键知识:通过给子对象添加属性index得到该元素的索引号。
说明:该程序通过遍历给每个button添加一个事件,在任意一个按钮上点击获得this.index,即所点元素的索引号。