2016-08-16 9 views
0

クリックすると、最も近いdivにテキストがあります。ここに私のコードは悲しげに動作しない、これまでです:リンクをクリックして、最も近い要素を見つける

$('.products').on('click', function(e) { 
 
    e.preventDefault(); 
 

 
    var pID = $(this).attr('data-pID'); 
 
    $(this).find('.categories').html(pID); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul style="margin-left:5px; margin-top:10px;"> 
 

 
    <li> 
 
    <a href="#" style="cursor:pointer;" class="products" data-pid="1">Product A</a> 
 
    <div class="categories"></div> 
 
    </li> 
 

 
    <li> 
 
    <a href="#" style="cursor:pointer;" class="products" data-pid="2">Product B</a> 
 
    <div class="categories"></div> 
 
    </li> 
 

 
</ul>

+0

を使用します。[ツリートラバーサル](https://api.jquery.com/category/traversing/tree-traversal/)、および[find()](https://api.jquery.com/find/)vs [next()](https://api.jquery.com/next/)。 – showdev

+0

@Damien:あなたも近づく必要はありませんか? 'prev()'や 'siblings()'のように? –

答えて

1

.findは、子要素を見ます。あなたのdivは子供ではない、それは兄弟ですので、参考のため.next

$(this).next('.categories').html(pID); 
+0

Doh!私はそれを見ていない、またはそれを知っていませんでした。入力いただきありがとうございます! – Damien

関連する問題