gpt4 book ai didi

javascript - 查找无序列表中 li 元素的编号

转载 作者:行者123 更新时间:2023-11-28 01:46:19 24 4
gpt4 key购买 nike

我需要在点击时找到无序列表中列表元素的编号。如果没有 JQuery,我将如何做这件事?

<ul>
<li><span>*</span>Cat</li>
<li><span>*</span>Dog</li>
<li><span>*</span>Avocado</li>
</ul>

例如,点击“猫”会给我 0,点击“狗”会给我 1,点击“鳄梨”会给我 2。

最佳答案

通常的技巧是找到点击来自的 LI,获取其父 UL 并遍历 LI 子级以找到主题 LI:

<ul id="ul0">
<li><span>first</span>
<li><span>second</span>
<li><span>third</span>
</ul>

<script>

document.getElementById('ul0').addEventListener('click', showIndex, false);

function showIndex(event) {
var index;
var element = event.target;

if (element.tagName.toLowerCase() != 'li') {
element = upTo('li', element);
}

if (element) {
index = getIndex(element);
}
console.log(index);
return index;
}

// Get the index of an LI in a UL
// Index is zero based
function getIndex(li) {
var ul = li.parentNode;
var node;
var nodes = ul.childNodes;

// Traverse child nodes, counting LIs until element found
for (var i=0, j=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i]

if (node.tagName && node.tagName.toLowerCase() == 'li') {

if (node == li) {
return j;
}
j++;
}
}
return null;
}

// Start from root and find ancestor with tagName
// Returns undefined if element not found
function upTo(tagName, root) {

if (!root) return;
tagName = tagName.toLowerCase();

while (root.parentNode) {
root = root.parentNode;

if (root.tagName && root.tagName.toLowerCase() == tagName) {
return root;
}
}
}
</script>

这也可以通过查看 LI 的父级是否是 OL 来处理 OL 中的 LI,如果是,则返回 li.value

关于javascript - 查找无序列表中 li 元素的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22498027/

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