jquery如何用each遍歷實現一個排異切換的效果?

chengxue_123發表於2020-12-13

1.給樣式

 <style>
        .rec{
            color:red;
        }
        .gre{
            color: green;
        }
    </style>

2.給標籤

  <ul>
       <li class="m">c</li>
       <li class="m">h</li>
       <li class="m">e</li>
       <li class="m">n</li>
       <li class="m">g</li>
       <li class="m">w</li>
       <li class="m">y</li>
       <li class="m">a</li>
    </ul>

3.給js,用each實現排異切換效果  

<script src="./jquery-3.3.1.min.js"></script>
<script>
    $('ul li').each(function(index,item){
        // if(index==5){
        //     var that=this;
        //    console.log(item);
        //    console.log($(that));
        //    $(that).click(function(){
        //        $(that).css('color','red');
        //    })
        // }
        var that=this;
        $(that).click(function(e){
            // console.log(e)
            $(that).addClass('rec').removeClass('gre').siblings().addClass('gre').removeClass('rec');
        })
    })
</script>

 

相關文章