如何遍历列表并应用 jQuery 来更改类

我正在学习 JavaScript。在下面的例子中,我试图

  1. 循环列表项以获取其原始类

  2. 更改。(具有红色类的列表项将变为绿色类,反之亦然)

我也想不断地改变它以获得动画效果。如何将javascript和jQuery一起添加?

我需要为每个列表项设置超时吗?

*<style>*

  .red{

        color:red;

    } 

    .green{

        color:green;

    }

*</style>*        





*<body>*

<ul class="list-inline-mb-0 ">

          <li  class="list-inline-item header red">C </li>

          <li class="list-inline-item header green">O</li> 

          <li class="list-inline-item header red">O</li> 

          <li class="list-inline-item header green">L</li> 


</ul>

*</body>*



*<script>*

  $(function()) {


    var myListElem = document.getElementsByClassName('li');


    $('li').each(function() {

    if(myListElem).hasClass("red"){           

     $(myListElem).addClass('green');

         }

    else{

        $(myListElem).addClass('red')

    }


    });  

*</script>*


慕丝7291255
浏览 151回答 1
1回答

狐的传说

首先,li不是一个类——list-inline-item是。其次,您不是在尝试遍历数组$('li').each(function()...,因为$('li')这不是您获取元素的方式。第三,即使修复循环并添加重复 ( setInterval()) 也不会给您动画,因为您只是添加类而不是删除它们。在您的示例中,当您检查red您时,然后添加green并获得red green结果类。总结所有所说的事情,这样的事情会做:$(function() {&nbsp; &nbsp; var myListElem = document.getElementsByClassName('list-inline-item');&nbsp; &nbsp; setInterval(function(){&nbsp; &nbsp; for(let i = 0; i < myListElem.length; i++){&nbsp; &nbsp; let e = myListElem[i];&nbsp; &nbsp; &nbsp; if($(e).hasClass("red")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;$(e).addClass('green');&nbsp; &nbsp; &nbsp; &nbsp;$(e).removeClass('red');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(e).removeClass('green');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(e).addClass('red');&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }, 3000);&nbsp; });.red{&nbsp; &nbsp; &nbsp; &nbsp; color:red;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; .green{&nbsp; &nbsp; &nbsp; &nbsp; color:green;&nbsp; &nbsp; }<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ul class="list-inline-mb-0 ">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li&nbsp; class="list-inline-item header red">C </li>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li class="list-inline-item header green">O</li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li class="list-inline-item header red">O</li>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <li class="list-inline-item header green">L</li>&nbsp;</ul>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript