原生实现点击li弹出相应索引

<style>
  .red{color: red}
</style>
复制代码
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
复制代码
<script>

  function exportIndex () {
    var li = document.getElementsByTagName('li')
    for (var i = 0; i < li.length; i++) {
      li[i].index = i
      li[i].onclick = function () {
        console.log(this.index)
        for (var j = 0; j < li.length; j++) {
          li[j].className = '' // 未选中的class为''
        }
        this.className = 'red' // 选中的class为'on'
      }
    }
  }
  
  exportIndex()
  
</script>
复制代码

转载于:https://juejin.im/post/5d0b14e1e51d455d6c0ad92e

猜你喜欢

转载自blog.csdn.net/weixin_33743248/article/details/93175265