检索子图像源(jQuery)

22
我有多个长这样的div:
<div><a href="our_work.html?clientid=39">
<img src="filestore/data_logos/39.gif" alt="client logo"/>
</a></div>

我正在尝试获取当点击 div 层时的图片链接:

$('#carousel div').click(function(event) {
  alert($(this).children('img').attr('src'));
});
警报始终返回为 null,有任何想法吗?
3个回答

35

6
.children() 仅返回直接子元素,而.find()会搜索所有的子元素,包括儿子、孙子等。 - gnarf

5

试试这个:

$('#carousel div').click(function(event) {
  alert($('img', this).attr('src'));
});

3

Straight from the horse's mouth,强调我的:

给定一个代表一组DOM元素的jQuery对象,.children()方法允许我们在DOM树中搜索这些元素的直接子级...

IMG像这样嵌套:DIV > A > IMG;你需要使用find()而不是children()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接