2012-01-12 88 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