我有以下HTML结构:
<div id="people-container">
<div class="col-md-4">
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
</div>
<div class="col-md-4">
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
</div>
<div class="col-md-4">
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
<div class="col-xs-4 people">
</div>
</div>
</div>
如你所见,我有9个人。我希望能够点击它们中的每一个,告诉我们点击了哪一个。
我可以得到他们的索引,但它会返回一个值{0,1,2},我也可以得到他们的父索引,但是相同的范围,{0,1,2}。 我想过将父母索引与它自己的索引相乘,但当然它不起作用,最大值为4,大多数值都是0 ......
如果有条件,我也不想做9。有更好的方法吗?
答案 0 :(得分:2)
要实现此目的,您可以使用index()
传递选择器将所需元素组合在一起。试试这个:
$('.people').click(function() {
console.log($(this).index('.people'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="people-container">
<div class="col-md-4">
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
</div>
<div class="col-md-4">
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
</div>
<div class="col-md-4">
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
<div class="col-xs-4 people">people</div>
</div>
</div>
&#13;
答案 1 :(得分:2)
将点击的div
及其父级索引存储在单独的变量中。可以通过以下公式访问当前div
的索引:
var currentIndex = 3 * parentIndex + clickedIndex;