Add nested hierarchy to the end of tel: link

I have a nested list item with deep sublevels. For example:

and

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

      

The last list is telephone communications. Let's say link for b, d, a<li><a class="tel-link" href="tel:8888">b,d,a</a></li>

How can I keep track of the hierarchy and add numbered sublevels to the end of the tel link so that it becomes <li><a class="tel-link" href="tel:8888,2,4,1">b,d,a</a></li>

and adds 2,4,1 to the end of the tel link?

Here's the jsFiddle

+3


source to share


1 answer


Use the jQuery function .index()

(see the docs, https://api.jquery.com/index/ )

If no argument .index()

is passed to any argument, the return value is an integer indicating the position of the first element in the jQuery object relative to its siblings.

I have demonstrated fiddle .



Selection is a recursive function:

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)))
})

      

This violin brings yours back desired_result - 1

. I left it like this because it's trivial to increment all values ​​by 1

, but it's easier to understand the code without incrementing.

+1


source







All Articles