如何在 jQuery 中将一个函数应用于多个图像?

发布于 2024-09-29 22:40:11 字数 406 浏览 0 评论 0原文

我需要一些(可能)非常简单的帮助。

我想使用一个将图像从彩色转换为灰度的脚本。 我让它部分工作 - 第一个图像变成灰色,但第二个图像不会。

我知道这是因为一个 id 不能多次使用:

var imgObj = document.getElementById('grayimage');

我尝试了这个:

var imgObj = $(’.grayimage’)[0];

但它不起作用。将其更改为 getElementByClass 也不起作用。 (在人们询问之前,我确实将 标记中的 id 更改为 class。)

我确实可以在这里使用一些帮助。提前致谢!

I need a little help with (probably) something really simple.

I want to use a script which converts images from color to grayscale.
I got it working partially — the first image turns gray, but the second won’t.

I know this is because an id cannot be used multiple times:

var imgObj = document.getElementById('grayimage');

I tried this:

var imgObj = $(’.grayimage’)[0];

But it didn’t work. Changing it to getElementByClass also does not work. (Before people ask, I did change the id to class in the <img> tag.)

I really could use some help here. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

征﹌骨岁月お 2024-10-06 22:40:11
$('.grayimage').each(function(idx,imgObj){
    <do your code here>
});
$('.grayimage').each(function(idx,imgObj){
    <do your code here>
});
王权女流氓 2024-10-06 22:40:11

$('.grayimage') 为您提供以grayimage 作为类的所有元素的列表。如果添加“[0]”,您将访问第一个元素,因此您所做的任何更改都将仅应用于在此类中找到的第一个图像。

您应该循环遍历所有元素:

var images = $('.grayimage');
for(i = 0; i < images.length; i++) {
   var image = images[i];

   // Do stuff
}

$('.grayimage') gives you a list of all elements with grayimage as a class. If you add '[0]' you're accessing the first element, so any changes you make will apply to only the first image that it finds with this class.

You should loop through all elements:

var images = $('.grayimage');
for(i = 0; i < images.length; i++) {
   var image = images[i];

   // Do stuff
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文