简体   繁体   中英

Change for loop result to reverse order in javascript/Jquery

Hi i have this javascript .

<html>
    <div>
        <li class="class0 class1" data-slide-to="0">Start</li>
     </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
     var i;
         for(i=0; i<3; i++){
             $(".class1").after("<li Class='class0' data-slide-to='"+i+"'>"+i+"</li>");
         }
      </script>  
</html>

And i get the out put as

Start
3
2
1
0

But i want to get this result in following order

start
0
1
2
3

how i get this ?How to revert the result?

Since you are using after() method it would append after the li . So get the parent and append the element. Although you need to update the condition in order to generate 4 elements and your HTML is not valid the li should be the child of ul or ol .

 <html> <div> <ul> <li class="class0 class1" data-slide-to="0">Start</li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> var i; for (i = 0; i < 4; i++) { $(".class1").parent().append("<li Class='class0' data-slide-to='" + i + "'>" + i + "</li>"); } </script> </html> 


Or geneate elements in reverse order.

 <html> <div> <ul> <li class="class0 class1" data-slide-to="0">Start</li> </ul> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> var i = 4; while (i--) { $(".class1").parent().append("<li Class='class0' data-slide-to='" + i + "'>" + i + "</li>"); } </script> </html> 

Change your script to work the other way around. So start at 3, and stop when you're at 0:

 <script>
     var i;
     for(i=3; i>0; i--){
         $(".class1").after("<li Class='class0' data-slide-to='"+i+"'>"+i+"</li>");
     }
  </script>  
<html>
<div>
    <li class="class0 class1" data-slide-to="0">Start</li>
 </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 var i;
     for(i=3; i>=3; i--){
         $(".class1").after("<li Class='class0' data-slide-to='"+i+"'>"+i+"</li>");
     }
  </script>  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM