How to pass an array to work in jquery

I want to pass an array to a function (can you tell me if im is on the right path?)

and then in the function that I want to iterate over the values ​​in the array and add each of them to the next LI element in HTML

This is what I so far the user encodes in the URL values ​​that he wants to pass:

var arrValues = ['http://imgur.com/gallery/L4CmrUt', 'http://imgur.com/gallery/VQEsGHz']; calculate_image(arrValues); function calculate_image(arrValues) { // Loop over each value in the array. var jList = $('.thumb').find('href'); $.each(arrValues, function(intIndex, objValue) { // Create a new LI HTML element out of the // current value (in the iteration) and then // add this value to the list. jList.append($(+ objValue +)); }); } } 

HTML

 <li> <a class="thumb" href="" title="Title #13"><img src="" alt="Title #13" /></a> <div class="caption"> <div class="download"> <a href="">Download Original</a> </div> <div class="image-title">Title #13</div> <div class="image-desc">Description</div> </div> </li> 
+6
source share
1 answer

If you want to pass an array, just enter it as a parameter. In Javascript, you can pass numbers, strings, arrays, objects, and even functions as parameters.

See this example for a thumbnail builder implementation: http://jsfiddle.net/turiyag/RxHys/9/

Define arrays first.

 var bluearray = [ 'http://fc02.deviantart.net/fs30/f/2008/056/8/0/Purple_hair___Bipasha_Basu_by_mstrueblue.jpg', 'http://static.becomegorgeous.com/img/arts/2010/Feb/20/1805/purple_hair_color.jpg', 'http://img204.imageshack.us/img204/6916/celenapurpleqp7.jpg' ]; var greenarray = [ 'http://25.media.tumblr.com/tumblr_m7fqmkNEhc1qlfspwo1_400.jpg', 'http://www.haircolorsideas.com/wp-content/uploads/2010/12/green-red-hair.jpg', 'http://fc02.deviantart.net/fs71/i/2010/011/9/c/Neon_Yellow_and_Green_Hair_by_CandyAcidHair.jpg' ]; 

Then, when the DOM is loaded, call the functions to load the thumbnails.

 $(function() { addThumbs(bluearray); addThumbs2(greenarray); }); 

addThumbs uses jQuery for each function to make things cleaner. I believe this looks better and it is better to use a regular Javascript for loop.

 function addThumbs(paths) { $.each(paths,function(index, value) { $("div").append('<img src="' + value + '" />'); }); } 

But if you are a fan of your own Javascript, the normal loop loop is implemented in addThumbs2

 function addThumbs2(paths) { for(index in paths) { $("div").append('<img src="' + paths[index] + '" />'); } } 
+6
source

All Articles