jquery attr将id添加到现有元素 [英] jquery attr add id to existing element

查看:595
本文介绍了jquery attr将id添加到现有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div里面有一堆imgs,上面有一个类,在我的JS中我有一个for循环,可以将图像重新调整为一个框内的fir而不会拉伸

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);

这是我试图让每个img拥有自己的ID,例如'img1''img2' 'img3'等

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

但它似乎不起作用

推荐答案

将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
});

这个代码块循环遍历每个IMG元素,计数器i在每个实例后递增,并且这个计数器后缀为id字符串。

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.

这篇关于jquery attr将id添加到现有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆