Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

jQuery .each() - Practical uses?

I am working on trying to better understand the jQuery.each() method. Here's an example I came up with, not very practical, but it performs an action on each selected item from the selected set of elements returned:

// Loop over each link.
$( "#links a.number" ).each(

// For each number, run this code. The "intIndex" is the 
// loop iteration index on the current element.
function( intIndex ){

// Bind the onclick event to simply alert the iteration index value.
    $( this ).bind ("click", function(){
        alert( "Numbered index: " + intIndex );
    });
});

What are some examples of practical uses of the .each method you are using in your code? What exactly does $(this) represent?

question from:https://stackoverflow.com/questions/722815/jquery-each-practical-uses

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note there are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.

Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)

 var hrefs = "";

 $("a").each(function() { 
     var href = $(this).attr('href');
     if (href != undefined && href != "") {
         hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);
     }
 });

 alert(hrefs);

Utilities/jQuery.each
Iterating over an array or the elements of an object: (via: jQuery Documentation)

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...