2016-05-22 4 views
0

を使用して、HTML要素の子孫にアクセスすることができません:D私は親の子の<code>html()</code>値の取得に問題が持っているjQueryの

機能 voteup(e)

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>

を、私がする必要があります'count'クラスの値を取得しますが、値を取得しませんhtml()

+0

「voteup」の宣言を提供してください –

+4

この質問タイトルは、[Parenting.SE](http://parenting.stackexchange.com/)からこの質問のタイトルを借りるときに、そのような意味があります。 – WBT

+0

うわー、編集していただきありがとうございます...英語は母国語ではありません。申し訳ありません:S –

答えて

3

childrenはDOM treの1つのレベルのみをトラバースしますつまり、孫を見つけることはできません。

:それは任意の深HTML構造を横断するために、子供を見つけるためにと find - 複数見つけることができます parentsとは反対に、単一の最も近い一致を見つけた -

代わりに、.item見つけることclosestを使用

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の初心者です:) –

関連する問題