原文:http://www.cnblogs.com/wuchuanlong/p/5945286.html

方法一,动态添加click事件,并添加属性

var itemli = document.getElementsByTagName("li");
for (var i = 0; i < itemli.length; i++) {
    itemli[i].index = i; //给每个li定义一个属性索引值
    itemli[i].onclick = function () {
    alert("索引为:" + this.index);
  }
}

方法二,用闭包实现(常用)

var itemli = document.getElementsByTagName("li");
for (var i = 0; i < itemli.length; i++) {
  (function (n) {
    itemli[i].onclick = function () {
      alert("索引为:" + n);
    }
  })(i)
}

或者

var itemli = document.getElementsByTagName("li");
for (var i = 0; i < itemli.length; i++) {
  itemli[i].onclick = function (n) {
    return function () {
      alert("索引为:" + n);
    }
  }(i)
}

方法三,jquery实现(更简单)

$("ul li").click(function () {
  var item = $(this).index();
  alert("索引为:" + item);
})

最新文章

  1. Linux初识
  2. JS实现-页面数据无限加载
  3. 第一篇博客 iframe自适应高度
  4. js 中文乱码
  5. dubbo 解决Multicast java.net.SocketException: No such device
  6. libmysqlclient.so.15: cannot open shared object file: No such file or directory
  7. input的width和padding-left同时存在时IE兼容问题
  8. Activiti(工作流)学习资源总结
  9. 从零起步学python计划及感想
  10. js遍历 子节点 子元素
  11. junit忽略测试方法
  12. DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示
  13. XAMPP本地服务器打不开解决方案
  14. Centos 7环境下安装配置MySQL 5.7
  15. C++11 override 和 final 关键字
  16. vc++基础班[24]---系统各种路径信息的获取
  17. httpd does not appear to be running and proxying cobbler, or SELinux is in the way.
  18. 2017-2018-2 20155303『网络对抗技术』Exp9:Web安全基础
  19. Spring MVC学习摘要
  20. 国外(英文)——WPF较好的奇葩问题解决网站

热门文章

  1. linux - sftp, scp, rz, sz(文件传输命令)
  2. JS对象 屏幕分辨率的高和宽 window.screen 对象包含有关用户屏幕的信息。 1. screen.height 返回屏幕分辨率的高 2. screen.width 返回屏幕分辨率的宽
  3. KiCAD原理图更换库
  4. express 路由能力
  5. Java中static关键字的定义
  6. C# 三层架构的一个小练习(Winfrom与SQLite数据库组合)
  7. js正则删除字符串中的部分内容
  8. JMeter Http请求之content-type用法
  9. 攻防世界 MISC篇
  10. cdn 链接