I have made a division of paragraphs with information in each. I also have a division of images.
My goal is to use jquery to append the text in each paragraph to an attribute in each image called 'data-description'.
So the first paragraph put in the 'data-description' attribute for the first image, and the second paragraph put in the 'data-description' attribute for the second image, etc...
For instance this code will do it just for the first:
$('#galleria :first-child').attr('data-description', $('#descriptions :first-child').text());
..given that the #galleria div contains the images, and the #descriptions div contains the text.
I've attempted to use a variable which increases each time, or classes which apply to each in sequence, or arrays, but I've had no joy.
I hope this explanation makes some sense!
I'd appreciate any thoughts, thanks.
Try this:
$('#galleria img').each(function(i){
$(this).attr('data-description', $('#descriptions p:eq('+i+')').text());
});
Explanation:
I use $('#galleria img').each to execute a function for each image tag. The variable named 'i' is equal to the current element index in the list. Then, I retrieve the "i"-th p tag into #descriptions and I put it in the data-description tag of the current image.
I hope it makes sense.
Try this
$('#galleria img').each(function(k,v){
$(this).prop('data-description', $('#descriptions p').eq(k)').html());
i = i + 1;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.