简体   繁体   中英

Javascript statements are executing after return

Here is my code:

    $.each(json.ids, function(i, v) {
        if ($("#user").val() === v.username) {
            if ($("#pw").val() === v.password) {
                window.location = '/menu.html';
                return; //THIS RETURN
            }
            $("#errorblock").text("incorrect password").show().fadeOut(1000);
            return false;
        }
        event.preventDefault();
        $("#errorblock").text("no user found").show().fadeOut(1000);
    });

json is a variable containing data in json format. The weird thing is that once you enter the nested if ( if ($("#pw").val() === v.password) ), the window will correctly change to menu.html but the words "incorrect password" or "no user found" will flash right before the window is changed. I can fix this problem in some workaround way but I'm curious as to why that would happen -- shouldn't the return just stop execution of the code? Is there some syntax (or other) error here that I should fix to prevent this?

Rather than performing your logic in the each, find the user first before processing.

 var username = $("#user").val(); var password = $("#pw").val(); //find the user based on their username var user = $.grep(json.ids, function(user){ return user.username === username; }); //if you found a user, check their password if (user.length) { if (user[0].password === password) { //redirect them for good case window.location = '/menu.html'; } else { //show incorrect password message $("#errorblock").text("incorrect password").show().fadeOut(1000); } } else { //no user found, do whatever event.preventDefault(); $("#errorblock").text("no user found").show().fadeOut(1000); } 

I should note, however, that performing password validation on the frontend is a very bad idea .

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