jquery attr将id添加到现有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23072767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery attr add id to existing element
提问by Drew
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
我在一个 div 中有一堆 imgs,上面有一个类,在我的 JS 中,我有一个 for 循环,可以将图像重新调整大小以在框内冷杉而不拉伸
$('.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
这就是我试图让每个 img 拥有自己的 id,如 'img1' 'img2' 'img3' 等
but it seems to not work
但它似乎不起作用
回答by shrmn
Replace your for loop with:
将您的 for 循环替换为:
$('.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.
此代码块循环遍历每个 IMG 元素,计数器 i 在每个实例之后递增,并且此计数器后缀为 id 字符串。
回答by kennypu
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:
它返回DOMObject
而不是 jQuery 对象。您将需要使用.eq()
返回 i 处的 jQuery 元素:
$('.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?
但是请注意,您似乎试图将其"
作为 ID 名称的一部分包含在内。不幸的是,单引号和双引号不是 ID 名称的有效字符。请参阅HTML 中 id 属性的有效值是什么?
回答by Akinkunle Allen
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.
each()
在返回的 jQuery 对象上使用提供的方法。它遍历返回的集合中的元素。该each
方法采用一个回调函数,该函数将在 jQuery 对象中的每个元素上调用。该each
方法将 jQuery 对象中每个元素的索引作为它的第一个参数,元素本身作为它的第二个参数。
This would work:
这会起作用:
$('.gallery img').each(function(index, elem) {
$(this).attr('id', 'img' + index);
});