【问题标题】:Select the last img in 2 divs with the same class选择同一类的2个div中的最后一个img
【发布时间】:2012-05-08 22:08:32
【问题描述】:

我有两个具有相同类 .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,但这对我不起作用。

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

谢谢。

【问题讨论】:

  • 您通过 JS 而不是 CSS 这样做是有原因的吗? div.productList img:last-child { margin-left: 10px }
  • 请展示一些示例标记
  • 添加了标记。没有理由让 jQuery 超过 CSS。在这种情况下,我想使用 jQuery
  • 我可以在那里看到一个last 类。那有什么问题呢?只需使用类选择器 (.last)。
  • 我试图避免使用该类,而是使用 jQuery 来定位 img

标签: html css jquery-selectors jquery


【解决方案1】:

“更好”的纯 CSS 方式

我同意 Ethan 的观点,你应该只使用 CSS 来做到这一点,但是,使用 last-child 选择器(如他所建议的那样)只有在 img 标记实际上是最后一个 html 元素时才有效。 .productlist(即没有其他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 标签987654336@,那么对于那些较旧的浏览器(也适用于较新的 CSS3 浏览器)的解决方案是use the adjacent sibling selector

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

【讨论】:

  • 不错的解决方案。起初我对 CSS 解决方案持反对态度,但这种解决方案效果很好。
【解决方案2】:

一个工作的fiddle

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

【讨论】:

    【解决方案3】:

    要么像 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;
    }
    

    【讨论】:

      【解决方案4】:
      $('div.productList').each(function(){
        $('img:last', this).css('margin-left','10px')
      });
      

      CSS 解决方案:

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

      【讨论】:

        【解决方案5】:

        只需使用 css 即可:

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

        【讨论】:

        • 这个解决方案可能会失败,就像this fiddle illustrates,这取决于特定的 html 标记(@webworker 没有发布全部内容)。如果是这样的话,我已经发布了一些额外的解决方案来避免这些困难。
        猜你喜欢
        • 2015-06-14
        • 1970-01-01
        • 2022-01-07
        • 2020-01-21
        • 2014-09-26
        • 2011-09-21
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        相关资源
        最近更新 更多