[英]How to conditionally stop anchor from jump to it's link page
I have this problem, I want to conditionally stop the anchor from jump. 我有这个问题,我想有条件地阻止锚跳。
condition jump 条件跳跃
I tried to add some codes in my coditionFun function to conditionally stop it from jumping. 我试图在coditionFun函数中添加一些代码,以有条件地阻止其跳转。
function conditionFun() {
var flag=false;
if(flag){
console.log('you allowed anchor jump'); return true;
} else {
console.log('you stopped the anchor jump');return false;
}
}
I was hoping to get "you stopped the anchor jump" and DO NOT jump to " http://www.google.com.hk ", but it logged "you stopped the anchor jump" and immediately jump to " http://www.google.com.hk ", anyone help me with this? 我希望得到“您停止了锚点跳转”并且不要跳转到“ http://www.google.com.hk ”,但是它记录了“您停止了锚点跳转”并立即跳转到“ http:// www.google.com.hk ”,有人帮助我吗? thank you!
谢谢!
Using jQuery would be your best bet. 使用jQuery将是您最好的选择。 Then you can run your logic whenever the click event happens on the anchor:
然后,只要锚点上发生click事件,就可以运行逻辑:
<a id="anchor" href="url">Your link<a/>
$('#anchor').click(function(e){
var flag=false;
if(flag){
console.log('you allowed anchor jump');
} else {
//stops the default anchor action from running
e.preventDefault();
console.log('you stopped the anchor jump');
}
})
you can define your own cancel default function. 您可以定义自己的取消默认功能。
<a id="alink" href="www.google.com">Google</a>
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
function conditionFun(e) {
var flag=false;
if(flag){
console.log('you allowed anchor jump');
return cancelDefaultAction(e);
} else {
console.log('you stopped the anchor jump');
return cancelDefaultAction(e);
}
}
document.getElementById("alink").addEventListener("click", conditionFun);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.