Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery Foundation: Working with multiple selection results (each iterative approach)


May 30, 2021 Article blog



jQuery provides a .each() method to cycle through the selected results, and each time the function is executed, the function is passed a numeric value that matches the position of the element in the selected result as an argument (a shape variable from scratch). R eturning 'false' stops the loop (just as using 'break') in a normal loop. R eturns 'true' to jump to the next loop (as if using 'continue') in a normal loop.

Example 1:

<ul>

<li>第一列</li>

<li>第二列</li>

<li>第三列</li>

</ul>

<button>选中所有列</button>

Using the jQuery code below, when you click the button, all columns are selected and indexed after each column

$(document).ready(function() {

$('button').click(function(){

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

var str = "<b>"+index+"</b>";

$("li:eq("+index+")").append(str);

});

});

});

Note: Index is a shape variable from scratch.

Example two:

<ul>

<li>第一列</li>

<li>第二列</li>

<li class="mark">第三列</li>

<li class="mark">第四列</li>

</ul>

<button>选择列</button>

Using the jQuery code below, the class "mark" column is selected when the button is clicked

$(document).ready(function() {

$('button').click(function(){

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

if ($(this).is(".mark")){

this.style.color = 'blue';

}

});

});

});

If we only want to select the first class as "mark", we can use return false to stop the loop

$(document).ready(function() {

$('button').click(function(){

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

if ($(this).is(".mark")){

this.style.color = 'blue';

Return False; // Note this Return

}

});

});

});

Note: In the example above, I used $this, which is a jQuery object, and this, which is a DOM object. The jQuery object has an is method, but does not have a style method, and similarly, a DOM object has a style method, but not an is method.