我有一个具有深子级别的嵌套列表项。例如:
一个
a,a
a,b
a,b,a
a,b,b
b
b,a
b,b
b,c
b,d
b,d,a
b,d,b
最后一个列表是电话链接。
假设 b、d、a 的电话链接是 <li><a class="tel-link" href="tel:8888">b,d,a</a></li>
如何跟踪层次结构并将编号的子级别添加到电话链接的末尾,使其变为 <li><a class="tel-link" href="tel:8888,2,4,1">b,d,a</a></li>
并将 ,2,4,1 添加到 tel 链接的末尾?
这是一个 jsFiddle
最佳答案
使用 jQuery 的 .index()
函数(参见文档,https://api.jquery.com/index/)
If no argument is passed to the
.index()
method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
我整理了一个 fiddle 进行演示。
重点是递归函数:
function getAncestory(el)
{
if (el.parent().parent().is("li"))
// If this <li> element is a child, prepend the parent indices
return getAncestory(el.parent().parent()) + "," + el.index();
else
return el.index()
}
// Only register clicks on <li> elements that don't have children
// (there are other ways to do an equivalent selector)
$("li:not(:has(*))").click(function(event){
alert(getAncestory($(this)))
})
此 fiddle 返回您的 desired_result - 1
。我之所以保留它,是因为将所有值递增 1
很简单,但不递增代码更容易理解。
关于javascript - 将嵌套层次结构添加到 tel : link 的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623334/