2015-05-18 94 views
0

如何使用jQuery從id = overall answer div中的評級選定div中獲取文本?jQuery按類選擇最接近的子元素

我想動態地從整個父div內的那個div取文本「TESTING」。

<div class='answer' id="overall"> 
     <div class='rating'>1</div> 
     <div class='rating'>2</div> 
     <div class='rating'>3</div> 
     <div class='rating'>4</div> 
     <div class='rating selected'>TESTING</div> 
</div> 

<div class='answer' id="effort"> 
     <div class='rating'>1</div> 
     <div class='rating'>2</div> 
     <div class='rating'>3</div> 
     <div class='rating selected'>4</div> 
     <div class='rating'>TESTING</div> 
</div> 

我試圖做到這一點,它是空白的。

$(document.getElementById('overall')).find('.rating selected').text(); 

回答

2

您的代碼的工作,但你的選擇是錯誤的。這將是...

$(document.getElementById('overall')).find('.rating.selected').text(); 

注意點和ratingselected之間沒有空格。

不過,我認爲你是在複雜的事情......

$('#overall .selected').text(); 

例...

alert($('#overall .selected').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 

 
<div class='answer' id="overall"> 
 
     <div class='rating'>1</div> 
 
     <div class='rating'>2</div> 
 
     <div class='rating'>3</div> 
 
     <div class='rating'>4</div> 
 
     <div class='rating selected'>TESTING - selected</div> 
 
</div> 
 

 
<div class='answer' id="effort"> 
 
     <div class='rating'>1</div> 
 
     <div class='rating'>2</div> 
 
     <div class='rating'>3</div> 
 
     <div class='rating selected'>4</div> 
 
     <div class='rating'>TESTING - not selected</div> 
 
</div>

1

$( '#總體.rating.selected' ).html()