A guide to using $of this.index and $.each in jQuery

  • 2020-03-30 04:21:12
  • OfStack

In response to a request at work, toggle an effect of the tabs, varying the HTML according to the total number of content elements under each option (if the content under the TAB is empty, it equals XXX, otherwise XXX)
 


 $(function(){
         $(".bao").hide();
          $(".bao").eq(0).show();
          $(".head li").click(function(){
              $(this).addClass('cur').siblings().removeClass("cur");
              $(".bao").eq($(this).index()).show().siblings(".bao").hide()
              var a=$(".bao").eq($(this).index()).find('li')
              if(a.length<0){
                   alert(" I'm less than 0 ah !!")
              }
          });
          function moren(){
              var moren=$(".moren").find('li')
              if(moren.length==0){
                  alert(" I was empty ~ no ")
              }
          }
 })

The header of the TAB is called the header
 
The contents of the TAB are called contents
 
The first way I came up with (stupid way) :
 
The binding adds a click event. When the header is switched, the header gets the corresponding content according to its own index, and the total number of contents under each header is obtained by traversing the li element under the content.
 
Because this is what the click thing found, but I ignored the first element of the header, and I wanted it to be executed as soon as the browser refreshed, I added a class class to the first element of the header to judge the class class. Finally ~
 
I get what I want. When the number of = = 0 | |! When theta equals zero, I'm going to do what I want.
 
But consider that. I don't want it to be executed when I click on it. I want it to be executed for me after the browser refreshes and loads. So I am a rookie and helpless pain of a method
 
Another method feels better this way ~:
 


 $(function(){
          $(".bao").hide();
          $(".bao").eq(0).show();
          $(".head li").click(function(){
              $(this).addClass('cur').siblings().removeClass("cur");
              $(".bao").eq($(this).index()).show().siblings(".bao").hide()
          });
         var aaa= $(".bao ul")
         aaa.each(function(){
             var b=$(this).children('li').length
             alert(b)
             if(b==0){
                 $(this).append("<div> I am a 0 And then add it up </div>")
             }
         })
 })

This method USES $.each()
 
More convenient, so far to get the results I want. $.each() iterates through each content element and then gets what I want by getting the total number of li elements below the content itself


Related articles: