简体   繁体   中英

without alert page is not redirecting via jquery

i want to redirect my page to the url which is coming in my variable but its not working without alert.

if i put alert then its redirecting otherwise not.

$(document).ready(function(){
    $("a").click(function(){
    var newurl = 'http://www.xyz.com/' + $(this).attr('href');
      //$(this).attr(newurl,'href');
      window.location.href = newurl;
       alert(newurl);
    });
});

thanx in advance

anchor tag

<a href="includes/footer.jsp">new url</a>

Try the following

$(document).ready(function () {
    $("a").click(function (event) {
        var newurl = 'http://www.xyz.com/' + $(this).attr('href');
        window.location.href = newurl;
        event.preventDefault()
    });
});

You need to prevent the default event from propagating by using preventDefault() . The browser is redirecting to the href before jquery has a chance to change it. By using the alert, you are delaying the browser redirect and hence it appears to work.

add preventDefault to event handler, to prevent following the URL in the link:

$(document).ready(function(){
    $("a").click(function(e){
      e.preventDefault();
      var newurl = 'http://www.xyz.com/' + $(this).attr("href");
      window.location.href = newurl;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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