Ordering Code

I have a question about ordering my jquery code. I have a list of images, each of which has a unique identifier, and the click event displays a larger image and its information. Is there a way to do this with a loop similar to php foreach loop?

$(function() { $('img#cl_1').click(function() { $('div#left').html('display image').slideDown('fast'); $('div#right').html('display image info').slideDown('fast'); }); $('img#cl_2').click(function() { $('div#left').html('display image').slideDown('fast'); $('div#right').html('display image info').slideDown('fast'); }); $('img#cl_3').click(function() { $('div#left').html('display image').slideDown('fast'); $('div#right').html('display image info').slideDown('fast'); }); $('img#cl_4').click(function() { $('div#left').html('display image').slideDown('fast'); $('div#right').html('display image info').slideDown('fast'); }); /*so on and so forth*/ }); 
+4
source share
2 answers

If you do not want to use the class selector, you can also use something like this:

 $(function() { $('img[id^="cl_"]').click(function() { $('div#left').html('display image').slideDown('fast'); $('div#right').html('display image info').slideDown('fast'); }); }); 

This should work on any image with an element identifier that begins with 'cl_'. The class selector is definitely clean though.

+3
source

If “display image” and “display image information” are different values ​​for each image, try loading them into an array or retrieving them through AJAX. Then change the binding of your event to look like this:

 $('img.showStuff').click(showDetails); function showDetails() { var id = this.id; $('div#left').html(images[id]).slideDown('fast'); $('div#right').html(info[id]).slideDown('fast'); } 
+2
source

All Articles