Javascript 检索子 img src (jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2186096/
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
Retrieve child img src (jQuery)
提问by fire
I have multiple div's that look like this:
我有多个 div 看起来像这样:
<div><a href="our_work.html?clientid=39">
<img src="filestore/data_logos/39.gif" alt="client logo"/>
</a></div>
I am trying to get the image src if you click on the div layer:
如果您单击 div 层,我正在尝试获取图像 src:
$('#carousel div').click(function(event) {
alert($(this).children('img').attr('src'));
});
The alert always comes back as null, any ideas?
警报总是返回空值,有什么想法吗?
回答by Nick Craver
Use this:
用这个:
$('#carousel div').click(function(event) {
alert($(this).find('img').attr('src'));
});
The images aren't children of the div...they're children of the <a>which is a child of the div, need to go one more level down.
图像不是 div 的子元素……它们是 div 子元素的子元素<a>,需要再往下一层。
回答by Piskvor left the building
Straight from the horse's mouth, emphasis mine:
直接从马嘴里说出来,强调我的:
Given a jQuery object that represents a set of DOM elements, the .children() method allows us to search through the immediatechildren of these elements in the DOM tree...
给定一个表示一组 DOM 元素的 jQuery 对象,.children() 方法允许我们在 DOM 树中搜索这些元素的直接子元素......
The IMG is nested like this: DIV > A > IMG; what you need is find()not children().
的IMG嵌套这样的:DIV > A > IMG; 你需要的find()不是children()。
回答by m4olivei
Try this:
尝试这个:
$('#carousel div').click(function(event) {
alert($('img', this).attr('src'));
});
~Matt
~马特

