Jquery 使用类选择前一个元素

Jquery select previous element with class

本文关键字:一个 元素 选择 Jquery      更新时间:2023-09-26

我有3个元素:

<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>

单击target div我在 js 中测试.prev()函数

$(document).on('click','.target',function(){
    console.log($(this).prev().html());
    console.log($(this).prev('.first').html());
});

输出就像:"第二个未定义",但如果我正确理解 .prev() 用法的参数,应该像:"第二个第一"。那么我怎样才能获得某个类的第一个前一个元素呢?这是给你的小提琴:http://jsfiddle.net/0fzgzce5/

来自 jQuery 文档,

.prev()

说明:获取每个元素的前面的同级元素 匹配元素集,可选择由选择器筛选。

选择前面的所有同级元素,而不仅仅是 在相邻的同级之前,使用 .prevAll() 方法。

http://api.jquery.com/prevAll/

所以你应该使用console.log($(this).prevAll('.first').html());

你可以

利用sibling(),它将返回具有特定类的元素,并且与调用elment处于同一级别。但请确保在target之后没有相同的div

$(document).on('click','.target',function(){
    console.log($(this).siblings('.second').html());
    console.log($(this).siblings('.first').html());
});

演示

或者您可以使用prevAll()

$(document).on('click','.target',function(){
        console.log($(this).prevAll('.second').html());
        console.log($(this).prevAll('.first').html());
    });

演示

使用 prevAll() 而不是 prev()

$(document).on('click', '.target', function() {
  alert($(this).prevAll('.second').html());
  alert($(this).prevAll('.first').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>

您也可以使用 $("div:eq(3)") 来获取确切的元素。最好的例子是$("ul li:eq(3)")

在你的

第二个console.log()中,你的this仍然是.target的,它没有.first类,所以它说undefined

要获得第一次潜水,请执行以下操作:

console.log($(this).prev().prev().html());

Jquery .prev()总是紧接在兄弟姐妹前面。

如果您将选择器作为参数传递,它将过滤前面的元素以匹配,如果不匹配,它将返回 undefined,在您的情况下,这种情况正在发生

$('.target').prev().html() 

$('.target').prev('.second').html();

将返回"第二"

如果您传递除".second"以外的任何选择器,则始终返回未定义,因此,您的情况

$('.target').prev('.first').html();

是 exprected,返回 undefined,因为 '.first' 与前面的元素选择器不匹配。

更新:如果你想得到第一个使用

$('.target').prev().prev().html();