2012-01-12 112 views
3

我有一个jQuery变量,它不工作,它是最喜欢的,因为我不知道如何正确选择元素。我想下面的选择会的工作,但他们没有jquery树遍历不工作

JQUERY:

$('.upVote').click(function(e){ 
    e.preventDefault(); 
    var ratebox = $(this).find('.ratingBox'); //this variable isnt working 
    var answer_id = $(this).children('.record_id').attr('value'); //this one too 

HTML:

<p class='ratingBox'> $answerrating[$f]</p> 
<div class='answerBar'>"; 
    <a href='#' class='upVote vote'>Upvote</a> 
    &middot; 
    <a href='#' class='downVote vote'>Downvote</a> 
    <a class='answerTime'> $difference $periods[$j] ago</a> 
</div> 
<input type='hidden' name='record_id' value='$answerid[$f]' class='record_id' /> 

回答

2

两个find()children()将寻找比低的元素在DOM树目前 - 你正在寻找的元素都更高。试试这个:

var ratebox = $(this).closest('.answerBar').prev(".ratingBox"); 
var answer_id = $(this).closest('.answerBar').next('.record_id').attr('value'); 

Fiddle to prove it works

+0

谢谢。这是解决方案!我会尽快接受。 – kirby 2012-01-12 16:58:57

0

使用应利用parentprevnext。因为findchildren会在不符合标记的元素中查找。试试这个

$('.upVote').click(function(e){ 

    e.preventDefault(); 
    var ratebox = $(this).parent().prev('.ratingBox'); //this will work now 
    var answer_id = $(this).parent().next('.record_id').attr('value'); //this too 

}); 
+0

谢谢,但它没有奏效。我不明白为什么会下一个工作。接下来得到下一个元素?或选择器中的下一个元素? – kirby 2012-01-12 16:56:23

+0

为什么这不起作用?这应该按照您的标记工作。 – ShankarSangoli 2012-01-12 17:09:18