Jquery manipulation object array element method

  • 2020-03-30 04:25:59
  • OfStack

The code is as follows:


 <div id="div1">
     <span>a</span>
     <span>b</span>
     <span>c</span>
 </div>

1. The wrong way : cannot use [] method to fetch jquery object array, as follows:


 $(function() {
     var div_span = $("#div1 span");
     for( var i = 0; i < div_span.length; i++ ) {
         div_span.[i].html(i);
     }
 });

It doesn't work.

May 2. Use the eq() method of jquery To select:


 for( var i = 0; i < div_span.length; i++ ) {
     div_span.eq(i).html(i);
 }

May 3. We're going to do it with the method each() :


 $(function() {
     var div_span = $("#div1 span");
     var i = 0;
     div_span.each( function(){
         $(this).html(i);
         i++;
     });
 });

When traversing each(), if you use $(this), you get a jquery object; if you use this directly, you get a DOM object

4 .array of DOM objects obtained by pure js code , you can get array elements in the form of []

The latter three are correct methods, the first is wrong, put him in the first, because to emphasize that the future can not make the same mistake, friends can look carefully.


Related articles: