查找按类筛选的元素的上一个匹配项

Find the previous occurrence of an element filtered by class

本文关键字:上一个 元素 筛选 查找      更新时间:2023-09-26

我有一个php循环,它以以下形式打印大量html:

<div class="something">
  ...
  <img class="prod-img" src="What-I-Need"/>
</div>
<div class="buttons" data-description="Some text here...">
  <a class="activator">Click me!</a>
</div> 

这段代码被重复了很多次。Usig jQuery我设法通过以下方式使用父选择器获取描述内容:

$('.activator').click(function() {
  alert($(this).parents('.buttons').data('description'));
})

由于$(this)有一个带有我需要的字段的父级,js代码运行得很好,我现在想知道,我如何检索类prod-img的src内容?由于在父目录之外…

如果它们像这个一样分组

<div class="container">
    <div class="something">
      ...
      <img class="prod-img" src="What-I-Need"/>
    </div>
    <div class="buttons" data-description="Some text here...">
      <a class="activator">Click me!</a>
    </div> 
</div>
<div class="container">
    .....etc....

使用.closest().find() 可以获得产品img

var src = $(this).closest('.container').find('.prod-img').attr('src');

否则,您需要使用.parent().prev().find(),这是非常静态的,使得在不更改代码的情况下更改HTML标记变得更加困难。

var src = $(this).parent().prev().find('.prod-img').attr('src');