For example, select a paragraph $ ("P ") In this way, all sections on the page are selected. Jquery provides . Each () Method to process the selected results cyclically, the function will pass the numeric value of the position where the matching element is located in the selected result as the parameter (an integer variable starting from scratch ). Return 'False' Will stop the loop (just like in a normal Loop 'Break' ). Return 'True' Jump to the next loop (just like in a normal Loop'Continue' ).
Example 1:
<Ul>
<Li> first column </LI>
<Li> second column </LI>
<Li> third column </LI>
</Ul>
<Button> select all columns </button>
// Use the following jqueryCode, Click the button, all columns will be selected, and the index is added after each column
$ ('Click'). Click (Function(){
$ ('Lil'). Each (Function(Index ){
VaRSTR ="<B>"+ Index +"</B>";
$ ("Li: eq ("+ Index +")"). Append (STR );
});
});
// Note: index is an integer variable starting from scratch.
Example 2:
<Ul>
<Li> first column </LI>
<Li> second column </LI>
<LiClass="Mark"> Third column </LI>
<LiClass="Mark"> Column 4 </LI>
</Ul>
<Button> select columns </button>
// Use the following jquery code. After you click the button, the column with class as "mark" will be selected.
$ ('Click'). Click (Function(){
$ ('Lil'). Each (Function(Index ){
If($ (This). Is (". Mark")){
This. Style. Color = 'Blue ';
}
});
});
// If you only want to select the first column whose class is "mark", you can use return false to stop the loop.
$ ('Click'). Click (Function(){
$ ('Lil'). Each (Function(Index ){
If($ (This). Is (". Mark")){
This. Style. Color = 'Blue ';
Return False;// Pay attention to this return
}
});
});
Note:In the above example, I used$ (This)AndThisThe former is a jquery object, and the latter is a DOM object. The jquery object hasIsMethod, but does not haveStyleSimilarly, DOM objects haveStyleMethod, but does not haveIsMethod.