JQuery: preventDefault for parent link only

DECISION:

Found a solution.

Used by parentNode:

$('.skaftetopmenu-li > a').click(function(e) { e.preventDefault(); var subid = $(this.parentNode).attr('id'); if (subid !="forsidemenu"){ var str = $('#submenu-content-'+subid).html(); if ($.trim(str) == ""){ $('.submenu-content', this.parentNode).load('http://' + skafte.base_url + '/inc/top-menu-subs/'+subid+'_submenu.html'); } } }); 

I have the following menu:

 <ul> <li class="parent"> <a href="url">Link title parent</a> <ul> <li><a href="url">Link title child</a></li> </ul> </li> </ul> 

I tried the following in jQuery:

 $('.parent').click(function(e) { e.preventDefault(); }); 

However, this disables all items in the entire menu structure. I only want to disable parent links. In "ul li" and not in the links in "ul ul li", but I canโ€™t understand how I searched and searched. So please help me!


EDIT: Thanks for the answers. I thought I would simplify my code in the question, but that really didn't help me. Thus, I am using the actual code that I am using:

 $('.skaftetopmenu-li').click(function(e) { var subid = $(this).attr('id'); if (subid !="forsidemenu"){ var str = $('#submenu-content-'+subid).html(); if ($.trim(str) == ""){ $('.submenu-content', this).load('http://' + skafte.base_url + '/inc/top-menu-subs/'+subid+'_submenu.html'); } } }); 

And HTML:

 <li class="skaftetopmenu-li" id="priser"> <a href="http://<?php echo DOMAIN?>/priser.php">Priser &amp; Sortiment</a> <div class="submenu-content" id="submenu-content-priser"></div> </li> 

If I try to do what you offer and install it:

 $('.skaftetopmenu-li > a').click(function(e) { e.preventDefault(); 

This does not work.

+4
source share
3 answers

Like Austin Mullins answer, I think you want this:

 $('li.parent > a').click(function(e) { e.preventDefault(); }); 
+7
source

Try the following:

 $(".parent > ul > li > a").click( function(e) { e.preventDefault(); // ... }); 

> matches only the nearest children of the previous tag.

0
source

This works for me on jsbin:

 $('.parent>a').on('click', function( e ){ e.preventDefault(); } ); 

http://jsbin.com/irojiq/1/edit

0
source

Source: https://habr.com/ru/post/1469338/


All Articles