zoukankan      html  css  js  c++  java
  • js循环给li绑定事件实现和弹出对应的索引

    原文: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);
    })
  • 相关阅读:
    React网络请求fetch之get请求
    英语学习
    人物传记
    四月
    启程
    情绪
    办公新址
    孩子大了
    幸福的生日
    hibernate---树状映射
  • 原文地址:https://www.cnblogs.com/sangzs/p/8615780.html
Copyright © 2011-2022 走看看