简体   繁体   English

如何使用 JQuery 阻止锚点重定向

[英]How to stop an anchor from redirecting using JQuery

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.我想用 JQuery 或 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/请使用http://api.jquery.com/event.preventDefault/

demo http://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 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
        }
    });
});​

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
    }
});

try this one试试这个

    $("a").on("click",function(e){
         e.preventDefault();
         alert("Clicked");

     });

happy Coding;快乐编码;

Use event.preventDefault() .使用event.preventDefault() It is used to prevent the default action of the event.它用于防止事件的默认动作。

<script type="text/javascript">
$(document).ready(function(){
      $('a').click(function(){
          var id = $(this).attr('id');
         if(id == 'yes'){
             event.preventDefault() 
         }else{
            //redirect
         }
     });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM