我想在单击时获取页面中每个元素的索引。但重点是索引不应该是item的通用索引,应该是根据tag的类型来的。
例如,考虑下面的例子。我已经提供了我得到的当前值以及预期的输出。
<div>First Div</div> <!-- This shows 0 (as required) -->
<div>Second Div</div> <!-- This shows 1 (as required) -->
<div>Third Div</div> <!-- This shows 2 (as required) -->
<div>
<p>First Para</p> <!-- This shows 0 (as required) -->
<p>Second Para</p> <!-- This shows 1 (as required) -->
<span>First Span</span> <!-- This shows 2 but I need it as 0 -->
<br/>
<span>Second Span</span> <!-- This shows 4 but I need it as 1 -->
</div>
<p>Third Para</p> <!-- This shows 4 but I need it as 2-->
<span>Third Span</span> <!-- This shows 5 but I need it as 2 -->
以下是我迄今为止尝试过的代码。应该如何修改以适应我的要求?
$(document).on("click", "*", function (e) {
e.stopPropagation();
index = $(this).index();
console.log(index);
});
这是一个带有当前代码的JSFiddle 。