我有3个要素:
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
在点击target
div
我测试.prev()
功能在我的js
$(document).on('click','.target',function(){
console.log($(this).prev().html());
console.log($(this).prev('.first').html());
});
输出是这样的:“二未定义”,而应该是这样的:“第二首”如果我的理解对不对.prev的参数()的用法。我怎样才能获得第一先前元素有一定的阶级呢?这里是捣鼓你:http://jsfiddle.net/0fzgzce5/
从jQuery的文档,
说明:获取每个元素的紧接在前的兄弟集合中的匹配元素,任选地通过一个选择器过滤的。
以选择所有前述兄弟元素,而不是仅仅根据前述相邻的兄弟,使用.prevAll()方法。
http://api.jquery.com/prevAll/
所以,你应该用console.log($(this).prevAll('.first').html());
您可以使用sibling()
的将与特定类别和级别相同调用elment返回元素。但要确保不存在同一个div target
后
$(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)")
在你的第二个qazxsw POI,你qazxsw POI仍qazxsw POI,它并没有console.log()
类,所以跟它this
。
为了让第一次潜水,这样做:
.target
jQuery的.first
总是直接前置兄弟。
如果你传递一个选择的参数,它会过滤前面的元素,以配合,如果不匹配就会返回undefined,你的情况,这种情况正在发生
undefined
是一样的
console.log($(this).prev().prev().html());
这将返回“第二”
如果传递不是'。第二个以外的任何选择它送花儿给人返回undefined所以,你的情况
.prev()
作为exprected,返回未定义的,因为“首先”不与元件选择前述匹配。
更新:如果你想获得首先使用
$('.target').prev().html()