2016-08-16 138 views
0

我试图有一个链接,点击后,会发现并把一些文字放在最接近的下来。这里是我到目前为止的代码,其可悲的是不起作用:点击一个链接,并找到最接近的元素

$('.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