What's wrong in this JavaScript code?

2019-09-21 04:36发布

问题:

I can't figure it out..

Markup:

<form>
    <fieldset><p>
        <label>Username: <input type="text" name="user" id="user" /></label></p><br /><p>
        <label>Password: <input type="password" name="passw" id ="passw" /></label></p>
        <label><input type="submit" value="Log in" name="submitBUT" style="width: 65px; height: 25px; background-color: green; color: white; font-weight: bold;" id="submitBUT" /><div id="helllo"></div></label>
    </fieldset>
</form>

Code:

var subBut = document.getElementById('submitBUT');
var users = ['hithere', 'Peter112', 'Geksj', 'lOsja', 'fInduS', '323DssaAA', 'f1fsus'];
var passes = ['mllesl', 'Petboy', 'Heneeesh', 'Olga', '234dasdf77/', 'minls', 'ew832ja'];
var output = [];
function submi(u, p) {
    for (var i = 0; i < users.length; i++) {
        if (users[i] == u) {
            output.push(i);
        }
    }
    for (var o = 0; o < output.length; o++) {
        if (passes[output[o]] == p) {
            return p + ' was a correct password.';
        }
    }
    return 'Error, please try again';
}
subBut.onclick = (document.getElementById('helllo').innerHTML=(submi(document.getElementById('user').value, document.getElementById('passw').value)));

LIVE CODE; http://jsfiddle.net/w87MS/

and yes, I know you don't store passwords in the source code :D, it's just "fur t3h lulz"

回答1:

I have to agree with comments above, not sure what you're doing but...the problem is that a submit handler is a function not the string you're assigning, this:

subBut.onclick = (document.getElementById('helllo').innerHTML=(submi(document.getElementById('user').value, document.getElementById('passw').value)));

should be:

subBut.onclick = function() { 
  document.getElementById('helllo').innerHTML=
    submi(document.getElementById('user').value, document.getElementById('passw').value);
  return false; //for testing, prevent form submission
}; 

You can test the updated version here.