---
title: "Javascript批量给元素添加事件"
author: "itway"
date: "2016-03-28T23:56:12Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2016-03-28T23:56:12Z"
id: 2286992
url: "https://itfinder.iteye.com/blog/2286992"
---

```
var stars = document.getElementsByTagName("i");
```

 首先获取所有i标签

 

```
for (var i=0;i<stars.length;i++){
        			stars[i].index = i;
        		}
```

 为每个标签添加自定义属性index，值为标签的key值

 

```
for (var i=0;i<stars.length;i++) {
        			stars[i].onmouseover = function(){
        				lightStars(this.index);
        			}
        			stars[i].onmouseout = function(){
        				offStars(this.index);
        			}
        			stars[i].onclick = function(){
        				alertStars(this.index);
        			}
        		}
```

 通过循环为每一个元素添加事件，注意的一点是，获取index值的时候，需要用this，而不是stars\[i]。