繁体   English   中英

jQuery选择类的前一个元素

[英]Jquery select previous element with class

我有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'的选择器,则它总是返回undefined,因此,您的情况

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

正确,返回undefined,因为“ .first”与前面的元素选择器不匹配。

更新:如果您想先使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM