I have a bunch of imgs inside a div with a class on them, in my JS I have a for loop that re-sizes the images to fir inside a box without stretching

$('.gallery img')[i].attr('id', 'img' + i);

This is what I tried to get each img to have its own id like 'img1' 'img2' 'img3' etc

but it seems to not work

有帮助吗?

解决方案

Replace your for loop with:

$('.gallery img').each(function(i) {
    $(this).attr('id', 'img' + i);
    // You can also add more code here if you wish to manipulate each IMG element further
});

This block of code loops through each IMG element with a counter i incrementing after every instance, and this counter is suffixed to the id string.

其他提示

when you do:

$('.gallery img')[i]

it returns the DOMObject and not a jQuery object. you will need to use .eq() to return the jQuery element at i:

$('.gallery img').eq(i).attr('id', 'img' + '"' + i + '"');

NOTE however, it looks like you are trying to include " as part of the id name. Unfortunately, single quotes and double-quotes are not valid characters for an ID name. see What are valid values for the id attribute in HTML?

Use the each() method provides on the returned jQuery object. It iterates over the elements in the returned set. The each method takes a callback function that will be invoked on each element in the jQuery object. The each method is passed the index of each element in the jQuery object as its first argument and the element itself as its second argument.

This would work:

$('.gallery img').each(function(index, elem) {
  $(this).attr('id', 'img' + index);
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top