如何停止使用JQuery重定向锚点 [英] How to stop an anchor from redirecting using JQuery

查看:119
本文介绍了如何停止使用JQuery重定向锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未登录,如何停止将锚标记重定向到另一个页面?我有一个函数来检查用户是否登录。我想用JQuery或JavaScript来做。这是迄今为止我尝试过的,但没有结果:

 < a href =www.somewhere.comid =是>阅读更多< / a> 

< script type =text / javascript>
$(document).ready(function(){
$('a')。click(function(){
var id = $(this).attr('id') ;
if(id =='yes'){
//我想阻止
} else {
//重定向
}
}) ;
});
< / script>


解决方案

请使用

http://api.jquery.com/event.preventDefault/ 演示 http://jsfiddle.net/aRBY4/6/

  e.preventDefault()



> quote `


如果调用此方法,事件不会被
触发。


另外,如果我可能会建议阅读:



希望这有帮助,

>

示例代码

  $('a' ).click(function(event){
event.preventDefault();
//做任何
}

在你的

请试试这个

  $(document).ready(function(){
$(' a')。click(function(event){
var id = $(this).attr('id');
if(id =='yes'){
event.preventDefault();
//我想阻止
} else {
//重定向
}
});
});


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:

<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>

解决方案

Please use

http://api.jquery.com/event.preventDefault/ demo 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()

hope this helps,

sample code

  $('a').click(function(event){
    event.preventDefault();
    //do whatever
  }  

In your case please 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
        }
    });
});​

这篇关于如何停止使用JQuery重定向锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆