[英]Stop <a> tag from loading href value
我有这样的事情:
<a href="http://example.com">
<span>text</span>
<button class="hello">hello</button>
</a>
当用户单击<button>
我不希望页面转到父<a>
标记的href值。 有什么方法可以在不将按钮移到锚标记之外的情况下阻止其重定向?
因此,钩入按钮:
jQuery( document ).on( 'click', '.hello', function() {
// STOP redirect
});
有什么解决方案?
您可以使用e.preventDefault();
以防止页面转到href URL。
jQuery(document).on('click', '.hello', function(e) { e.preventDefault(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="http://example.com"> <span>text</span> <button class="hello">hello</button> </a>
因此,您可以执行以下操作:
<a href="www.example.com">
<span>text</span>
<button class="hello" id="btnhello">hello</button>
</a>
接着
$('#btnhello').onclick((ev) => {
ev.preventDefault();
ev.stopPropagation();
});
您可以使用按钮来调用事件阻止默认值,因此许多浏览器都不会执行提交默认行为,并且事件stopPropagation不允许将事件传播到父级,即单击按钮时的锚点。
您是否尝试过此代码?
window.jQuery('.hello').click(function(event){ event.preventDefault(); alert("YaY!"); });
是的,您可以使用preventdefault
它阻止标准行为,或者您可以在click函数中返回false
<a href="/" onclick="return false">Press </a>
or
<a href="/" onclick="event.preventDefault()">Press </a>
ruturn false将阻止它重定向到任何其他页面:
jQuery( document ).on( 'click', '.hello', function() {
// your Code goes here
// STOP redirect
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.