2016-05-22 85 views
0

我有得到一個html()值父母的孩子的問題一個HTML元素的後代:d無法訪問使用jQuery

function voteup(e){ 
 
    var count = $(e).parents('.item').children('.count'); 
 
    console.log(count.html()); // undefined 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="post_contain"> 
 
    <img src="images/comments/dQ6dz.jpg" alt=""> 
 
</div> 
 
<div class="item"> 
 
    <p class="post-meta"> 
 
    <span href="/gag/agVzE1g" target="_blank"> 
 
     <span class="count">5</span>points 
 
    </span> 
 
    </p> 
 
    <div class="vote"> 
 
    <ul class="btn-vote left"> 
 
     <li class="badge-item-vote-up-li"> 
 
     <a onclick="voteup(this)">Click me</a> 
 
     </li> 
 
    </ul> 
 
    </div> 
 
</div>

在功能voteup(e),我需要得到類'count'的值,但我沒有檢索到值html()

+0

請提供的聲明'voteup' –

+4

這個問題頭銜從[Parenting.SE(http://parenting.stackexchange.com/)跨越它的到來時,這種不同的含義。 – WBT

+0

哇,謝謝你的編輯...英語不是我的母語,我很抱歉:S –

回答

3

children只能遍歷DOM tre電子 - 即它不會找到孫子。

相反,使用closest找到.item - 它找到一個最接近的匹配,而不是parents可以找到多 - 和find找到孩子,因爲這會遍歷任意深度的HTML結構:

function voteup(e){ 
    var count = $(e).closest('.item').find('.count'); 
    alert(count.html()); 
    var actual = parseInt(count.html(), 10); 
    count.text(actual + 1); 
} 
+0

謝謝!我是JQuery和JS的初學者:) –