可能重复:
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>