简体   繁体   中英

Javascript Check Login function returns false, but continues to next line anyways?

The following code checks for a user and returns false if the user is not logged in.

  function checkLogin(e) {
    loggedIn = $('#loggedin').text();
    if(loggedIn == '1'){
      e.preventDefault();
      alert("Please Log In");
      return false;
    }
  }

I then call this function before some other code and an ajax call.

tileFavorite = $('.tileFavorite');
tileFavorite.on('click', function(e) {
      checkLogin(e);

     //some code goes here before ajax call

    $.ajax({
        url: // ajax call goes here,
        cache: false
    })
});

The check login actually works. However if the checkLogin function returns false, it still continues to the code beneath it. There a way to avoid this?

You're doing nothing to prevent that code from being called.

Try:

  function checkLogin(e) {
    loggedIn = $('#loggedin').text();
    if(loggedIn == '1'){
      e.preventDefault();
      alert("Please Log In");
      return false;
    }

    return true;
  }

tileFavorite.on('click', function(e) {
    if (! checkLogin(e))
      return false;

     //some code goes here before ajax call

    $.ajax({
        url: // ajax call goes here,
        cache: false
    })
});

Try this

tileFavorite.on('click', function(e) {
  if(false == checkLogin(e)){
    return false;
  }
     //some code goes here before ajax call

    $.ajax({
        url: // ajax call goes here,
        cache: false
    })
});

tileFavorite on click should return value to stop execution.

It looks like you aren't doing anything with the false that is actually returned. You could try:

if (checkLogin(e)) {
    ...
    $.ajax(
        ...
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM