jQuery:仅在父链接上防止默认 [英] jQuery: preventDefault on parent link only

查看:56
本文介绍了jQuery:仅在父链接上防止默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案:

找到了解决方案.

使用的父节点:

$('.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 a menu like this:

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

我在 jQuery 中尝试了以下内容:

I have tried the following in jQuery:

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

然而,这会禁用整个菜单结构中的所有元素.我只想禁用父链接.ul li"中的那些,而不是ul ul li"中的链接,但我不知道我是如何搜索和搜索的.所以请帮帮我!

However this disables all the elements in the whole menu structure. I want to only disable the parent links. The ones in "ul li", and not the links in "ul ul li", but I can't figure out how and I have searched and searched. So please help me out!

感谢您的回答.我以为我会在问题中简化我的代码,但这实际上对我没有好处.所以这是我正在使用的实际代码:

Thank you for the answers. I thought I would simplify my code in the question but that actually didn't benifit me. So heres the actual code I'm 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');
      }
   }
});

还有 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 as you suggest and set it to:

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

它不起作用..

推荐答案

类似于 Austin Mullins 的回答,我想你想要这个:

Similar to Austin Mullins' answer, I think you want this:

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

这篇关于jQuery:仅在父链接上防止默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆