gpt4 book ai didi

javascript - 根据标签类型获取页面中元素的索引

转载 作者:行者123 更新时间:2023-11-29 18:20:27 26 4
gpt4 key购买 nike

我想在点击时获取页面中每个元素的索引。但重点是索引不应该是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使用当前代码。

最佳答案

您当前的代码正在获取每个标签相对于其父标签的索引。需要修改如下,根据标签类型获取当前点击元素的索引。

index = $(this.tagName).index(this);

FIDDLE

关于javascript - 根据标签类型获取页面中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19206170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com