javascript - How to disable all links inside a nested ul, except for the ones at the lowest level? -
let's have list, this:
<ul> <li><a href="sitepages/introduction.aspx">introduction</a> <ul> <li><a href="sitepages/aboutme.aspx">about me</a></li> <li><a href="sitepages/aboutthecompany.aspx">about company</a> <ul> <li><a href="sitepages/history.aspx">history</a></li> <li><a href="sitepages/locations.aspx">locations</a> <ul> <li><a href="sitepages/belgium.aspx">belgium</a></li> <li><a href="sitepages/france.aspx">france</a></li> <li><a href="sitepages/germany.aspx">germany</a></li> <li><a href="sitepages/norway.aspx">norway</a></li> </ul> </li> </ul> </li> </ul> </li> </ul>
i have script turns nested ul accordion top levels shown @ first. clicks on link inside li containing ul, expands ul , on.
the thing is, while works fine when no links provided, want disable default behavior of every "a" tag, except ones @ lowest level. li tags @ lowest level, link inside them, should still active links.
here's javascript code disables default behavior of top level links:
$this.find("li").each(function(){ if ($(this).find("ul").size() != 0) { if ($(this).find("a:first")) { $(this).find("a:first").click(function(){ return false; }); } });
while top level link (introduction) ignore default behavior (redirecting) upon clicking, expand , show "about me" , "about company" options. when click on "about company", still redirects.
what should edit in code set default behavior of every "a" tag false, except last ones (in example: country names)?
thanks help!
you can setup 2 handlers. 1 disable links within unordered list , handle clicks on last unordered list:
// disable links within ul $('ul').on("click", "a", function(e){ e.preventdefault(); }); // second handler bind last ul $('ul:last').on("click", "a", function(e){ window.location.href = $(e.target).attr('href'); });