开发者

how to stop a hashtag's default click behaviour? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Stop default hashtag behavior with jquery

I have some jquery code on a link that loads a DIV into the page using .load(), it also adds a hashtag to the url for pagination / bookmarking purposes; what i want to do is to stop the page from jumping to the div when the link is clicked.

$('#jqNav li a').click(function(){

    if($(this).parent().is(".nav1")){ $('.landing .main .nav ul').css({ "background-position" : "0 -50px" });} 
    else if($(this).parent().is(".nav2")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -100px" });}
    else if($(this).parent().is(".nav3")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -150px" });}
    else if($(this).parent().is(".nav4")) {    $('.landing .main .nav ul').css({ "background-position" : "0 -200px" });};


    stopAnim = true;
    $page = $(t开发者_如何学Pythonhis).attr('href');
    var $hashTag = $(this).attr('name');
    window.location = "#" + $hashTag;
    loadData();
    e.preventdefault();
    return false;

});


Try using use e.preventDefault(); on the link click

Try using $(window).scrollTop(0); to prevent the # from affecting the page


You can use e.preventDefault() for this

http://api.jquery.com/event.preventDefault/

Or use:

return false;

Which does both preventDefault() and stopPropagation()

http://api.jquery.com/event.stopPropagation/

EDIT

Don't think what you want can be done. Since it would be bad security wise to be able to change the URL of a page without going to that URL.

You can for example change the URL to the URL of a bank letting users think your page represent the bank.

Maybe it works when only adding a hash so you can give the following a try (haven't tested it, might very well not work):

window.location.hash = $hashTag;
return false;

EDIT2

I know I just told you it doesn't work however I just stumbled upon this post here on SO which uses HTML5 to do what you want:

Is there a way to change the browser's address bar without refreshing the page?

Again not tested :)


You could use return false; as the last statement in the click-handler. That or use both event.preventDefault() and event.stopPropagation() (return false is equal to the both of them together, preventing the default behaviour for that element and preventing the event from bubbling up through the DOM).

References:

  • event.preventDefault()
  • event.stopPropagation()
  • event.preventDefault() vs. return false (at Stack Overflow)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜