Jquery how to work with arrays

//1. Basic jQuery.each() Function Example //display all "a" on the page in console $('a').each(function (index, value){ console.log($(this).attr('href')); }); //2. jQuery.each() Array Example var numbers = [1, 2, 3, 4, 5, 6]; $.each(numbers , function (index, value){ console.log(index + ':' + value); }); //This snippet outputs: 0:1, 1:2, 2:3, 3:4, 4:5, and 5:6. //3. jQuery.each() JSON Example var json = [ { 'red': '#f00' }, { 'green': '#0f0' }, { 'blue': '#00f' } ]; $.each(json, function () { $.each(this, function (name, value) { console.log(name + '=' + value); }); }); //This example outputs red=#f00, green=#0f0, blue=#00f. //4. jQuery.each() Class Example //Example HTML code /* <div class="productDescription">Red</div> <div>Pink</div> <div class="productDescription">Orange</div> <div class="generalDescription">Teal</div> <div class="productDescription">Green</div> */ $.each($('.productDescription'), function (index, value) { console.log(index + ':' + $(value).text()); }); //In this case the output is 0:Red, 1:Orange, 2:Green. /* We don’t have to include index and value. These are just parameters which help determine on which DOM element we are currently iterating. Furthermore, in this scenario we can also use the more convenient each method. We can write it like this: */ $('.productDescription').each(function () { console.log($(this).text()); }); /*And we’ll obtain on the console: Red Orange Green */ //5. jQuery .each() Delay Example /*In the next example, when the user clicks the element with the ID 5demo all list items will be set to orange immediately. After an index-dependent delay (0, 200, 400, … milliseconds) we fade out the element.*/ $('#5demo').bind('click', function (e) { $('li').each(function (index) { $(this).css('background-color', 'orange') .delay(index * 200) .fadeOut(1500); }); e.preventDefault(); }); /*We should make use of the each() function as much as we can. It’s quite efficient and it’ll save us heaps of time! Thinking outside of jQuery we may want to prefer using the forEach() function of any ECMAScript 5 array. Remember: $.each() and $(selector).each() are two different methods defined in two different ways.*/

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.