如何在jQuery中禁用链接?以前我正在更改锚点的href属性,但意识到这不是阻止用户进入新页面的最佳方法。我在属性中添加了disabled true,但这不起作用。点击仍然需要工作 - 我只是不希望锚点中的链接激活。
var acc = document.getElementsByClassName("dropdown-nav");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active-hit");
this.find('a').attr('disabled', true);
//this.find("a").attr("href", "#");
});
}
<ul>
<li class="dropdown-nav">
<a href="/about">About
<span class="nav-desc">Our company</span>
</a>
<div class="hide-border"></div>
<ul class="second-tier">
<div class="hide-corner"></div>
<li><a href="#">Our Mission</a></li>
<li><a href="#">Our People</a></li>
<li><a href="#">Work with us</a></li>
<li><a href="#">High Value Manufacturing</a></li>
</ul>
</li>
</ul>
答案 0 :(得分:3)
您可以向点击功能添加一个事件(e
)参数,并使用e.preventDefault();
停止跟踪该链接。
var acc = document.getElementsByClassName("dropdown-nav");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].addEventListener("click", function(e) {
this.classList.toggle("active-hit");
e.preventDefault();
});
}
<ul>
<li class="dropdown-nav">
<a href="/about">About
<span class="nav-desc">Our company</span>
</a>
<div class="hide-border"></div>
<ul class="second-tier">
<div class="hide-corner"></div>
<li><a href="#">Our Mission</a></li>
<li><a href="#">Our People</a></li>
<li><a href="#">Work with us</a></li>
<li><a href="#">High Value Manufacturing</a></li>
</ul>
</li>
</ul>
继续发表评论后更新了jQuery解决方案:
var $dropdown = $('.dropdown-nav > a');
$dropdown.on('click', function(e){
$(this).parent().toggleClass('active-hit');
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="dropdown-nav">
<a href="/about">About
<span class="nav-desc">Our company</span>
</a>
<div class="hide-border"></div>
<ul class="second-tier">
<div class="hide-corner"></div>
<li><a href="#">Our Mission</a></li>
<li><a href="#">Our People</a></li>
<li><a href="#">Work with us</a></li>
<li><a href="#">High Value Manufacturing</a></li>
</ul>
</li>
</ul>
答案 1 :(得分:0)
我喜欢使用&#39;&#39;
$("a").on('click', function(event) {
event.preventDefault();
alert('default link action prevented');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://www.google.com" target="_blank">Some link</a>
&#13;
答案 2 :(得分:0)
只需将pointer-events: none;
css属性添加到您不想单击的元素即可。它使你的指针看不到它。
然后只需使用js
根据需要切换此类。
.noClickAllowed {
pointer-events: none;
}
<ul>
<li class="dropdown-nav noClickAllowed">
<a href="/about">About
<span class="nav-desc">Our company</span>
</a>
<div class="hide-border"></div>
<ul class="second-tier">
<div class="hide-corner"></div>
<li><a href="#">Our Mission</a></li>
<li><a href="#">Our People</a></li>
<li><a href="#">Work with us</a></li>
<li><a href="#">High Value Manufacturing</a></li>
</ul>
</li>
</ul>