0
<ul id="menu">
    <li data-main="1">
        <a href="/controller/action"></a>
        <ul data-submenu="1">
           <li><a href="/controller/action"></a></li>
        </ul>
    </li>
</ul>

Someone clicks on the inner anchor element. How do I retrieve the data-submenu value and the data-main value?

0

2 Answers 2

1

Something like:

$("#menu a").click(function() {
    var submenu = $(this).closest("ul#menu").find("[data-submenu]").data("submenu");
    var main = $(this).closest("ul#menu").find("[data-main]").data("main");
});
Sign up to request clarification or add additional context in comments.

7 Comments

@A.Wolff -- Haha...ohhh yess
But, now it's also bound to the outer <a> as well. ;)
@talemyn OP's question is quite confusing concerning that :(
Yeah, definitely need some more details to give exactly the right answer. I took "Someone clicks on the inner anchor element" to mean the lowest level <a> in his sample code, but it's definitely a little ambiguous . . .
I should really look at the code closer, didn't even notice that second a on the outer.
|
0

Since you were asked to retrieve the values while clicking on the inner anchor element, I just given the code accordingly. Actually this complication in selecting that anchor element can be removed by providing an id to it.

Reason for using the cache variable(xFirstLevel) : In order to reduce the unnecessary dom traversal.

Try this out,

$("#menu li li > a").click(function(){

    var xFirstLevel = $(this).closest("ul");

    alert(xFirstLevel.data('submenu'));
    alert(xFirstLevel.closest('li').data('main'));

});

DEMO

1 Comment

Thank you, That's what I was looking for. Not very familiar with closest(). I'll have to familiarize myself with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.