Get index of parent div from child divs

假装没事ソ 提交于 2019-11-28 08:04:44

问题


I have a few divs and inside them I have nested divs. I would like to be able to get the index of the parent div my child divs reside in. Ie: If I clicked "post5" I would get the index1 or If I clicked "post4" it would still get index 1.

Html:

 <div class="more-content">
   <div class="post">post 1</div>
   <div class="post">post 2</div>
   <div class="post">post 3</div>
 </div>
<div class="more-content">
  <div class="post">post 4</div>
  <div class="post">post 5</div>
  <div class="post">post 6</div>
</div>
 <div class="more-content">
  <div class="post">post 7</div>
  <div class="post">post 8</div>
  <div class="post">post 9</div>
 </div>

Jquery:

$(".post").click(function() {
    alert($(".post").parent.index(this));
});

回答1:


The following should work:

$(".post").click(function() {
    var index = $(this).parent().index(".more-content");
    alert(index);
});

DEMO: http://jsfiddle.net/NDySY/



来源:https://stackoverflow.com/questions/13162206/get-index-of-parent-div-from-child-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!