2010-02-02 86 views
15

我有多个div的看起来像这样:检索子IMG SRC(jQuery的)

<div><a href="our_work.html?clientid=39"> 
<img src="filestore/data_logos/39.gif" alt="client logo"/> 
</a></div> 

我想,如果你点击div层上,以获得图像的src:

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

的警报总是回来为空,任何想法?

回答

25

使用此:

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

的图像是不是DIV的孩子......他们是<a>这是div的孩子的孩子,需要去一个多级下调。

+5

+1 - '.children()'将只返回**直接后代**其中'.find()'将搜索下面的所有元素;儿童,孙辈等 – gnarf 2010-02-02 17:19:03

2

尝试这种情况:

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

〜马特

3

Straight from the horse's mouth,重点煤矿:

如果提供的jQuery代表了一组DOM元件,所述。儿童()方法允许我们通过立即这些元素在DOM树中的子...

IMG嵌套如下:DIV > A > IMG;你需要的是find()而不是children()