jquery toggle: clicking on link jumps back to top of the page

前端 未结 2 1253
甜味超标
甜味超标 2020-12-31 01:35

I created a jquery toggle, but when I click the link to open a div it will jump to the top of the page. how can I fix this?

I know I could replace the link with some

2条回答
  •  抹茶落季
    2020-12-31 02:21

    Add return false; to the end of the code that runs when you click the link.

    $('a.myLink').toggle(function() {
        // run my code
        return false;
    });
    

    Alternatively, you can grab the event object, and call .preventDefault().

    $('a.myLink').toggle(function(event) {
        event.preventDefault();
        // run my code
    });
    

    Both of these methods disable the default behavior of the link.

    The first one will also prevent the event from bubbling, so use it only if you have no need to utilize the event bubbling.

提交回复
热议问题