选择具有相同类的2个div中的最后一个img

时间:2012-04-28 10:54:59

标签: html css jquery-selectors jquery

我有两个具有相同类.productList的div,并希望使用jQuery操纵两个div中的第二个<img>

我有以下内容;

$('div.productList').each(function(){
    $('img:last-child').css('margin-left','10px');
});

标记(部分)

<div class="productList">
<img src="images/parts/" width="120" height="120" alt="" title="" />
<img class="last" src="images/parts/" width="120" height="120" alt="" title="" />

我假设使用.each()会遍历每个div并找到最后一个img,但这对我不起作用。

有人可以指出我正确的方向吗?

感谢。

5 个答案:

答案 0 :(得分:5)

只需使用css即可:

div.productList img:last-child {
    margin-left: 10px;
}

答案 1 :(得分:2)

“更好”纯CSS方式

我同意Ethan你应该使用CSS来做到这一点,但是,使用last-child选择器(正如他所推荐的)只有img标签实际上是 .productlist中的最后一个html元素(即没有其他divspan等在img标记 - see example之后。由于您只显示了部分标记,因此我完全不清楚。如果它只是一系列img标签,那么请使用Ethan的答案,否则......

更好的CSS3解决方案是使用last-of-type,因为它只会查找正在搜索的类型的元素(在这种情况下为img)。因此,如果其他元素遵循它,it does not matter

.productList img:last-of-type {
    margin-left: 10px;
}

对于不支持CSS3的旧版浏览器,如果您的两个img代码实际上在您的标记中一个接一个地坐着,并且它们是唯一的配对img .productList中的标签,那么旧版浏览器的解决方案(也适用于较新的CSS3浏览器)将是use the adjacent sibling selector

.productList img + img {
    margin-left: 10px;
}

答案 2 :(得分:1)

要么像Ethan所说的那样使用CSS,但是如果你在jQuery 中这样做,那么绝对不需要.each语句。只需使用jQuery选择最后一项:

$('.productList img:last-child').css('margin-left','10px');

在此处查看:

http://jsfiddle.net/Willyham/PM8eG/

CSS解决方案:

div.productList img:last-child {
    margin-left: 10px;
}

答案 3 :(得分:0)

$('div.productList').each(function(){
  $('img:last', this).css('margin-left','10px')
});

CSS解决方案:

div.productList img:last-child {
    margin-left: 10px;
}

答案 4 :(得分:0)

工作fiddle

   $('div.productList').each(function(){
        $(this).find('img:last').css('margin-left','50px');
   });