SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Wizard silver trophybronze trophy
    Join Date
    Jul 2008
    Location
    New York, NY
    Posts
    1,432
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    jQuery each function

    Hi all,

    I usually do something like this for toggling each individual span, but was wondering if anyone uses the each function instead?

    I find I never use the each function for any front-end functionality.

    Would any of you guys use the each function for an example like this?

    If so show me an example of how you would do such....

    Code HTML4Strict:
    <ul>
    	<li><a href="#">item</a> <span>text</span></li>
    	<li><a href="#">item</a> <span>text</span></li>
    	<li><a href="#">item</a> <span>text</span></li>
    	<li><a href="#">item</a> <span>text</span></li>
    	<li><a href="#">item</a> <span>text</span></li>
    </ul>
    Code CSS:
    span { display: none; }
    Code JavaScript:
    $(function() {
    	$('li a').toggle(function() {
    		$(this).parent().find('span').show();
    	},
    	function() {
    		$(this).parent().find('span').hide();
    	});
    });
    When I code using core JavaScript I always use the for loop and that is why i'm asking

  2. #2
    SitePoint Wizard silver trophybronze trophy
    Join Date
    Jul 2008
    Location
    New York, NY
    Posts
    1,432
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I set some examples up last night using the each function. There is really no point to use the each function I feel for something like this

  3. #3
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The each method is just a convenient iterator. When you need to loop through an array, object or a DOM collection you can use 'each'. A primative implementation of 'each' would be as follows:

    Code JavaScript:
    function each(arr, fn) {
        for (var i = 0, len = arr.length; i < len; i++) {
            fn(arr[i], i);
        }
    }
     
    // Usage:
    var nodes = $('div');
    each(nodes, function(node, i) {
        // Do something with 'node'
    });

    jQuery's 'each' method is not too different; here it is: (from jQuery 1.3.2)

    Code JavaScript:
    var name, i = 0, length = object.length;
     
    if ( args ) {
    	if ( length === undefined ) {
    		for ( name in object )
    			if ( callback.apply( object[ name ], args ) === false )
    				break;
    	} else
    		for ( ; i < length; )
    			if ( callback.apply( object[ i++ ], args ) === false )
    				break;
     
    // A special, fast, case for the most common use of each
    } else {
    	if ( length === undefined ) {
    		for ( name in object )
    			if ( callback.call( object[ name ], name, object[ name ] ) === false )
    				break;
    	} else
    		for ( var value = object[0];
    			i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
    }
     
    return object;

    Dependent on the passed object it will loop through it in one of a few different ways; all essentially doing the same thing.

    A regular JavaScript loop (for(){}, while(){}) allows you to break from it or continue to the next iteration using the continue and break keywords. jQuery lets you simulate such actions by returning false to 'break' from the loop; returning a non-false value will 'continue' the loop.

    So, essentially, the 'each' method is jQuery's shortcut to the regular JavaScript loop.

    --

    Now, for your example, you are correct; there is no need to use the 'each' method but it is definitely useful. Here are a couple of examples of where I've used 'each' in the past:

    Code JavaScript:
    // E.g. #1
    // Build a list:
    function buildColorList(colors) {
        var list = '';
        $(colors).each(function(){
    	list += ('<li><a href="#" style="background:' + this + '">&nbsp;</a></li>');
        });
        return list;
    }
     
    // E.g. #2
    // Run multiple actions on all '.post-content' elements
    $('#main .post-content').each(function(){
        var href = $(this).find('.bar > a:eq(0)').attr('href');
        $('p:last:not(.postmetadata)',this).append('&nbsp;(<a href="'+href+'">Continue Reading...</a>)');
    });

    If you're comfortable using JavaScript FOR loop then there really is no reason to use 'each'. In fact, using your own FOR loop will probably be faster (albeit marginally).
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  4. #4
    SitePoint Wizard silver trophybronze trophy
    Join Date
    Jul 2008
    Location
    New York, NY
    Posts
    1,432
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @JimmyP

    Oh okay I see.

    Thanks for the well articulated response


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •