Javascript 如何阻止锚使用 JQuery 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11240897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop an anchor from redirecting using JQuery
提问by Ankit
How can I stop an anchor tag redirecting to another page if the user is not logged in? I have a function to check if the user is logged in or not. I want to do it with JQuery or JavaScript. Here is what I have tried so far but with no results:
如果用户未登录,如何阻止锚标记重定向到另一个页面?我有一个功能来检查用户是否登录。我想用 JQuery 或 JavaScript 来做。这是我迄今为止尝试过但没有结果的方法:
<a href="www.somewhere.com" id="yes">Read More</a>
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
var id = $(this).attr('id');
if(id == 'yes'){
//i want to prevent
}else{
//redirect
}
});
});
</script>
回答by Tats_innit
Please use http://api.jquery.com/event.preventDefault/
请使用http://api.jquery.com/event.preventDefault/
demohttp://jsfiddle.net/aRBY4/6/
演示http://jsfiddle.net/aRBY4/6/
e.preventDefault()
quote
引用
If this method is called, the default action of the event will not be triggered.
如果调用此方法,则不会触发事件的默认动作。
Also if I may suggest read this: .prop() vs .attr()
另外,如果我建议阅读此内容:.prop() vs .attr()
Hope this helps,
希望这可以帮助,
sample code
示例代码
$('a').click(function(event){
event.preventDefault();
//do whatever
});
In your caseplease try this
在你的情况下,请试试这个
$(document).ready(function() {
$('a').click(function(event) {
var id = $(this).attr('id');
if (id == 'yes') {
event.preventDefault();
//i want to prevent
} else {
//redirect
}
});
});?
回答by slash197
Change your click event handler to this
将您的点击事件处理程序更改为此
$('a').click(function(e){
var id = $(this).attr('id');
if (id == 'yes')
{
e.preventDefault();
e.stopPropagation();
}
else
{
//redirect
}
});
回答by Adeel Ahmed Baloch
try this one
试试这个
$("a").on("click",function(e){
e.preventDefault();
alert("Clicked");
});
happy Coding;
快乐编码;
回答by Nishu Tayal
Use event.preventDefault(). It is used to prevent the default action of the event.
使用event.preventDefault()。它用于防止事件的默认操作。
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
var id = $(this).attr('id');
if(id == 'yes'){
event.preventDefault()
}else{
//redirect
}
});
});
</script>