javascript - 将嵌套层次结构添加到 tel : link 的末尾

标签 javascript jquery

我有一个具有深子级别的嵌套列表项。例如:

一个

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/

相关文章:

jquery - 点击功能关闭所有打开

javascript - 通过 JavaScript 点击 Flash 对象

javascript - 如何访问对象数组内嵌套对象的 JSON 属性

javascript - 如何在 JavaScript 中从 html 引用 iframe

javascript - Node.js:如何序列化/反序列化 React 组件?

javascript - 使用 javascript 对象创建 highchart 饼图

javascript - 如何通过多个条件过滤js对象?

javascript - 集合检查框 = 集合检查框

javascript - 在 JavaScript 中访问数据库值

javascript - 如何在具有动态键值对的javascript中解析json?