我有3个要素:
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
Run Code Online (Sandbox Code Playgroud)
点击target div我.prev()在我的js 测试功能
$(document).on('click','.target',function(){
console.log($(this).prev().html());
console.log($(this).prev('.first').html());
});
Run Code Online (Sandbox Code Playgroud)
输出如下:'Second undefined',但应该是:'second first'如果我理解了.prev()用法的参数.我怎样才能获得某个类的第一个前一个元素呢?这是小提琴:http://jsfiddle.net/0fzgzce5/
来自jQuery文档,
描述:获取匹配元素集中每个元素的前一个兄弟,可选择由选择器过滤.
要选择所有前面的兄弟元素,而不仅仅是前面的相邻兄弟元素,请使用.prevAll()方法.
http://api.jquery.com/prevAll/
所以你应该使用 console.log($(this).prevAll('.first').html());