4

我有两个具有相同类的 div .productList,并且想<img>用 jQuery 操作两个 div 中的第二个。

我有以下内容;

$('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="" />

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

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

谢谢。

4

5 回答 5

5

只需使用 css 来做到这一点:

div.productList img:last-child {
    margin-left: 10px;
}
于 2012-04-28T11:06:46.973 回答
2

“更好”的纯 CSS 方式

我同意 Ethan 的观点,你应该只使用 CSS 来做到这一点,但是,使用last-child选择器(如他所建议的那样)只有在img标签实际上是最后一个 html 元素 .productlist时才有效(即标签后面没有其他div,span等) img- -见例子)。由于您只显示了部分标记,因此我完全不清楚。如果只是一系列img标签,那么使用Ethan的答案,否则......

更好的 CSS3 解决方案是使用last-of-type,因为它只会查找正在寻找的类型的元素(img在这种情况下)。因此,如果其他元素跟随它,也没关系

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

对于不支持 CSS3 的旧浏览器,如果您的两个img标签实际上在您的标记中一个接一个地放置,并且它们是 中唯一成对的img标签.productList,那么对于那些旧浏览器的解决方案(这也适用于较新的 CSS3浏览器)将使用相邻的兄弟选择器

.productList img + img {
    margin-left: 10px;
}
于 2012-04-28T13:24:33.647 回答
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;
}
于 2012-04-28T11:11:58.870 回答
0
$('div.productList').each(function(){
  $('img:last', this).css('margin-left','10px')
});

CSS解决方案:

div.productList img:last-child {
    margin-left: 10px;
}
于 2012-04-28T10:57:32.510 回答
0

一个工作小提琴

   $('div.productList').each(function(){
        $(this).find('img:last').css('margin-left','50px');
   });
于 2012-04-28T11:25:18.117 回答