문제

I have a stupid simple Jquery .js file I'm busy creating and I'm getting stuck on the first step.

I currently have it setup as shown below and yet every time I click the only button on the page (submit button for a login page), it reloads the entire page and runs the first function again.

How do i get the function to only run once

$(document).ready(function() {
    //
    //  FUNCTIONS 
    //

    function AllFade() {
        //Hide everything
        $('div').hide()

        //Fade Everything in
        $('div').fadeIn(1000);

        //Hide All Alerts
        $('.alert').hide();
    }

    function LoginCheck() {
        //Check username and pass
    }   

    //   EVENTS     

    //START SEQUENCE
    AllFade();

    //Login check on submit
    $('.btn').click(function() {
        LoginCheck();
    })
});

!! EDIT !!

The button's coding is this exactly:

<button class="btn btn-large btn-primary">Sign in</button>

Would that still cause a reload?

도움이 되었습니까?

해결책

You need to prevent the submit (event) of the form with .preventDefault() so it will not do the default behaviour: submit the form and reload the page.

$('.btn.btn-large.btn-primary').click(function(event) { 
   //if only button on page you can have just $('button')
    event.preventDefault()
    LoginCheck();
})

You can also add type="button" if you do not want to use the button as a submit button, because the button element has a default type of submit:

<button type="button" class="btn btn-large btn-primary">Sign in</button>


You can read more here:

jQuery docs: .preventDefaul()

다른 팁

Add an event in there and use .preventDefault()to prevent the page from reloading.

$('.btn').click(function(e) {
    e.preventDefault();
    LoginCheck();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top