I have a simple menu that has an arrow within the anchor. I have jQuery that adds a class to show the arrow on click. However I need it to NOT "show the arrow" on click if the clicked li a doesn't have a submenu. Here's a rough example of my menu:
<ul id="menu">
<li><a href="#">TopLevel_LinkOne <img src="img/down-carat.png" class="down-carat"></a></li>
<li><a href="#">TopLevel_LinkTwo <img src="img/down-carat.png" class="down-carat"></a></li>
<li><a href="#">TopLevel_LinkThree <img src="img/down-carat.png" class="down-carat"></a>
<ul class="sub-menu">
<li><a href="#">Submenu Link One <img src="img/down-carat.png" class="down-carat"></a></li>
<li><a href="#">Submenu Link Two <img src="img/down-carat.png" class="down-carat"></a></li>
<li><a href="#">Submenu Link Three <img src="img/down-carat.png" class="down-carat"></a></li>
</ul>
</li>
</ul>
In this example I do not want the arrow to show, if "TopLevel_LinkOne" or "TopLevel_LinkTwo" is clicked. I can't remove the arrow image because it's being added automatically by the nav walker in Wordpress.
Here's my jQuery:
$('#menu li a').click(
function() {
$('ul li a').removeClass('show-arrow'); // Remove any previous arrows
if('some jquery here that checks if THIS has submenu') {
$(this).addClass('show-arrow'); // Show the arrow image
}
});
Try this:
if($(this).parent().find('ul').length) {
$(this).addClass('show-arrow'); // Show the arrow image
}
Try,
if($(this).closest('li').find('.sub-menu').length > 0)
Full code:
$('#menu li a').click(function() {
$('ul li a').removeClass('show-arrow'); // Remove any previous arrows
if($(this).closest('li').find('ul.sub-menu').length) {
$(this).addClass('show-arrow'); // Show the arrow image
}
});
If your HTML allows you to make certain assumptions, you can do this really easily.
For example, if it's a safe assumption that your list items will only ever contain either "just a single <a>
element", or "a single <a>
element followed by a submenu", then you can just do:
if( this.parentNode.children.length > 1)
But if you want robustness, you could do this:
if( $("ul",this.parentNode).length)
try this way
JQUERY CODE:
$('#menu li a').click(function() {
$('ul li a').removeClass('show-arrow'); // Remove any previous arrows
if($(this).siblings('ul').length) {
$(this).addClass('show-arrow'); // Show the arrow image
}
});
LIVE DEMO: http://jsfiddle.net/dreamweiver/MHg67/3/
Happy Coding :)
This one might just work for you:
$('#menu > li').click(function () {
$('ul li a').removeClass('show-arrow');
$(this).has('ul.sub-menu').addClass('show-arrow');
}
You can modify it accordingly to suit your needs. Thanks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.