js循环给li绑定事件实现和弹出对应的索引
2024-09-27 23:20:23
原文: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);
})
最新文章
- Linux初识
- JS实现-页面数据无限加载
- 第一篇博客 iframe自适应高度
- js 中文乱码
- dubbo 解决Multicast java.net.SocketException: No such device
- libmysqlclient.so.15: cannot open shared object file: No such file or directory
- input的width和padding-left同时存在时IE兼容问题
- Activiti(工作流)学习资源总结
- 从零起步学python计划及感想
- js遍历 子节点 子元素
- junit忽略测试方法
- DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示
- XAMPP本地服务器打不开解决方案
- Centos 7环境下安装配置MySQL 5.7
- C++11 override 和 final 关键字
- vc++基础班[24]---系统各种路径信息的获取
- httpd does not appear to be running and proxying cobbler, or SELinux is in the way.
- 2017-2018-2 20155303『网络对抗技术』Exp9:Web安全基础
- Spring MVC学习摘要
- 国外(英文)——WPF较好的奇葩问题解决网站
热门文章
- linux - sftp, scp, rz, sz(文件传输命令)
- JS对象 屏幕分辨率的高和宽 window.screen 对象包含有关用户屏幕的信息。 1. screen.height 返回屏幕分辨率的高 2. screen.width 返回屏幕分辨率的宽
- KiCAD原理图更换库
- express 路由能力
- Java中static关键字的定义
- C# 三层架构的一个小练习(Winfrom与SQLite数据库组合)
- js正则删除字符串中的部分内容
- JMeter Http请求之content-type用法
- 攻防世界 MISC篇
- cdn 链接