jQuery中的index用法与inArray用法

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    .score {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    .score li {
      display: inline-block;
      width: 50px;
      height: 50px;
      border: 1px solid #f00;
      border-radius: 50%;
      cursor: pointer;
    }
  </style>
</head>
<body>

<h3>请打分</h3>
<ul class="score">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

<script src="js/jquery-1.11.3.js"></script>
<script>
  //获得当前单击的li在所有li中的位置i,i及其执行的都变为红色,i之后的都变为白色
  $("ul.score").on("click","li",function(){
   
    var $i=$(this);
    var lis=document.querySelectorAll("ul.score>li");
    var i=//$("ul.score>li").index(this);
         // $(this).index();
         /*这里的this代表当前的li元素,整句话的意思是代表这个的位置是多少,
          结果是数字,这里是有局限性的,必须当前获取的li是都在一个ul的,不然会出错,
          从0开始排列,把获取到的li类数组进行编号*/
          $.inArray(this,lis);//这个API可以获取到当前的li在lis(类数组对象)中的位置
    $("ul.score>li:lt("+(i+1)+")").css("background","red");
    $("ul.score>li:gt("+i+")").css("background","#fff");

  })
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/shuen/p/8781343.html