jQuery click brings me to top of page. But I want to stay where I am

前端 未结 5 1380
长发绾君心
长发绾君心 2020-12-09 06:14

I have a simple click and show, click and hide button, but when I click it, the page anchors at the top of the page. Is there anyway to prevent this? So that when I click th

相关标签:
5条回答
  • 2020-12-09 06:54

    Try this:

    $('#reportThis').hide();
    
    $('#flagThis').click(function (evt) {
            $('#reportThis').show("slow");
            evt.preventDefault();
    });
    $('#submitFlag').click(function (evt) {
            $('#reportThis').hide("slow");
            evt.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-09 07:01

    Try returning false in the click function:

    $('#reportThis').hide();
    
    $('#flagThis').click(function () {
            $('#reportThis').show("slow");
            return false;
    });
    $('#submitFlag').click(function () {
            $('#reportThis').hide("slow");
            return false;
    });
    
    0 讨论(0)
  • 2020-12-09 07:05

    You probably are binding this clicks to a <a> tag which has a default action. To prevent this you can use another tag like <div> or you can do this:

    $('#flagThis').click(function (event) {
            $('#reportThis').show("slow");
            event.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-09 07:05

    If you're using a <button> element don't forget to set the type attribute.

    <button type="button">My Button</button> 
    

    Some browsers default to submit which will bring you back to the beginning of your page.

    It's where I was going wrong anyway and saw nothing here about it so thought I'd share my two cents for future readers.

    0 讨论(0)
  • 2020-12-09 07:19

    Change the hyperlinks to point to a non-existent anchor, like this:

    <a href="#IDontExist" id="flagThis">Flag</a>
    

    Or, make your handlers return false, like this:

    $('#reportThis').hide();
    
    $('#flagThis').click(function () {
        $('#reportThis').show("slow");
        return false;
    });
    $('#submitFlag').click(function () {
        $('#reportThis').hide("slow");
        return false;
    });
    
    0 讨论(0)
提交回复
热议问题