使用 jquery,如何选择 div 内的图像来更改其源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8440315/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:32:46  来源:igfitidea点击:

using jquery, how can i select an image inside of a div to change its source

jqueryhtmlselector

提问by leora

I have the following div and I know the selector Id of the DIV.

我有以下 div,我知道 DIV 的选择器 ID。

 <div class="event"><img src="/Content/Images/Icons/calendar16.png">Event Name</div>

but I don't know what the image is. I need something to find the image selector inside the div that i have so i can go change the source of the image to a new image.

但我不知道图像是什么。我需要一些东西来在我拥有的 div 中找到图像选择器,这样我就可以将图像源更改为新图像。

回答by Jasper

$('.event').children('img').attr('src', '<source here>');

This selects all the elements with the eventclass and then finds their children imgelements. If you have multiple matches and want to change their sources differently then you can use $.each()to iterate through them.

这将选择具有event该类的所有元素,然后找到它们的子img元素。如果您有多个匹配项并希望以不同的方式更改它们的源,那么您可以使用$.each()它们来迭代。

A demo: http://jsfiddle.net/aPzgR/

演示:http: //jsfiddle.net/aPzgR/

回答by Serge

$('div.event img').attr('src', '/anything');

If you have several divs with eventas the class you're better off selecting the div by id if you don't want to change the source of all the images

如果您有多个 divevent作为类,如果您不想更改所有图像的源,最好按 id 选择 div