2

我有以下 HTML ..

<div class = "thumbnail">
  <img src = "somePath">
</div>
 <div class = "thumbnail">
  <img src = "somePath">
</div>
<div class = "thumbnail">
  <img src = "somePath">
</div>
<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>
<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>

我想在div.thumbnail的第一个孩子下迭代img标签。我想过滤掉它们。我用作..

var i =0;
$("div.thumbnail :first-child").each(function() {
    console.log("Touch "+(++i)+" time(s) !");
    if($(this).context.nodeName.toLowerCase() == 'img') {
        console.log("Getting Image Tag.");
    }
});

我的问题是我想过滤获取元素..

$("div.thumbnail :first-child :img").each(function(){});

我不想迭代为div.thumbnail的计数。我想迭代为第一个子标签的div.thumbnail计数是img。如何弄清楚?

4

3 回答 3

2

使用:has() Selector

$("div.thumbnail:has( > img:first-child)").each(function(){});

jsFiddle 演示

于 2013-09-12T03:43:56.637 回答
1

简单的

$(".thumbnail > img").each(function(){
    //
});

这将跳过以下第一个孩子不是img

<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>

小提琴

于 2013-09-12T03:50:04.690 回答
1
$(".thumbnail:has('> img:first-child'),.thumbnail > img:first-child").each(function(){
     //TO Do here
});

演示

于 2013-09-12T04:21:26.097 回答