我希望在点击时获取页面中每个元素的索引。但重点是索引不应该是项目的一般索引,它应该基于标记的类型。
例如,请考虑以下示例。我已经提供了我得到的当前值以及预期的输出。
<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。
答案 0 :(得分:4)
您当前的代码是获取每个代码相对于其父代的索引。您需要按照以下方式对其进行修改,以根据标记类型获取当前单击元素的索引。
index = $(this.tagName).index(this);