如果父对象hasClass()阻止链接的默认设置 [英] Prevent default on link if parent hasClass()
本文介绍了如果父对象hasClass()阻止链接的默认设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简体HTML:
<ul>
<li class="no-link"><a>Should not be clickable</a>
<ul>
<li><a>Should be clickable</a></li>
<li><a>Should be clickable</a></li>
</ul>
</li>
</ul>
JavaScript:
Javascript:
jQuery(document).ready(function( $ ) {
$('a').parent().click(function(e) {
if($(this).hasClass('no-link')){
e.preventDefault();
}
});
})
在不应单击的链接上正常工作,但也会影响两个后代a
标记.为什么?我以为parent()
在DOM中只走了一步.
Works fine on the link that should not be clickable, but also affects the two descendant a
tags. Why? I thought parent()
only traversed up a single step in the DOM.
我要通过WordPress以编程方式添加该类(作为外观">菜单"控制面板中的一个选项),因此直接通过类定位a
标记并不是真正的选择.
I'm adding the class programatically via WordPress (as an option in the Appearance > Menus control panel), so targeting the a
tag directly via class is not really an option.
推荐答案
您想要的是实际捕获对a
元素的单击,然后检查其中的父类.
What you want is to actually capture the click on a
element and then check for parent class inside it.
只需将您的代码更改为:
Just change your code to:
$('a').click(function(e) {
if($(this).parent().hasClass('no-link')){
e.preventDefault();
}
});
这篇关于如果父对象hasClass()阻止链接的默认设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文