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

前端 未结 2 1254
甜味超标
甜味超标 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:23

    That is because there's a default action associated with elements like links, checkboxes, radio buttons etc. You can cancel it like so:

    $('a.mylink').click(function(ev) { // Pass in the event object to your function
        // do stuff
        ev.preventDefault();
        return false;
    });
    

    More information here: http://api.jquery.com/event.preventDefault/

    In the rare event of attaching an event handler to a child of a link you'll also want to use event.stopPropagation(), to stop the event bubbling up the DOM.

提交回复
热议问题