1

可能重复:
jquery 找到最近的同级同级

下面给出的代码运行良好

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div><span>Hello</span></div>

  <p class="selected">Hello Again</p>
  <p>And Again</p>
<script>$("p").prev(".selected").css("background", "yellow");</script>

</body>
</html>

但是当我将 .selected 移到顶部(如下所示)时,它不起作用。谁能告诉我如何让它为我工作并在第二种情况下从 .prev() 方法中获取 .selected 元素而不操作 html

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<p class="selected">Hello Again</p>//Moved to top
<div><span>Hello</span></div>

  <p>And Again</p>
<script>$("p").prev(".selected").css("background", "yellow");</script>

</body>
</html>
4

2 回答 2

4

You need to use .prevAll() instead of .prev(). The latter only checks the immediate predecessor which is div in your case. prevAll() however checks all prececessors so it will find your element. In case you have multiple predecessors matching your selector, use .prevAll('.selected').first() to get only the nearest one.

Demo: http://jsfiddle.net/ThiefMaster/GnEK5/

于 2012-05-14T09:45:26.693 回答
0

你可以试试

$('p').prevAll('.selected');
于 2012-05-14T09:41:41.427 回答