0

我刚开始学习 javascript,而且我已经使用 HTML 一段时间了。我知道我已经成功地为我的登录表单编写了正确的 JavaScript 代码。

这是我的 JavaScript 代码:


<script>
function login(){
    var username=document.getElementById('usrnm');
    var password=document.getElementById('pass');
    if(username=="abc"){
        if(password=="123"){
            window.location.href="mypage.html"
        }
        else{
            window.location.href="error.html"
        }
    else{
        window.location.href="error.html"
    }
}
</script>

这是我的 HTML 表单:


<form name="input" method="get">
<b>Username:</b>
<br>
<input id="usrnm" type="text" name="usrnm">
<br>
<br>
<b>Password:</b>
<br>
<input id="pass" type="password" name="pswrd">
<br>
<br>
<center>
<input id="login" type="image" src="login.png" value="login" onclick="login()">

当我点击登录按钮时。它只会重新加载它所在的同一页面,但如您所见,我打算调用“mypage.html”。我刚刚开始学习 JavaScript,所以如果有任何明显的原因导致我的代码无法正常工作,那就简单了。谢谢=)。我知道我的 JavaScript 可以工作,因为当我尝试插入onclick="login()"<form name="input" method="get"> 时,当我在“用户名”字段或“密码”字段中键入时,代码会将我定向到“error.html”。

4

4 回答 4

4

你没有得到元素值,只是元素。添加.valuedocument.getElementById(id)方法调用的末尾。

于 2013-08-08T12:07:07.060 回答
4

你的 JS 没有按预期工作。您正在选择元素,而不是它们的。尝试更改为以下内容:

<script>
function login(){
    var username=document.getElementById('usrnm').value;
    var password=document.getElementById('pass').value;
    if(username=="abc"){
        if(password=="123"){
            window.location.href="mypage.html"
        }
        else{
            window.location.href="error.html"
        }
    }
    else{
        window.location.href="error.html"
    }
}
</script>
于 2013-08-08T12:07:41.843 回答
0

获取 usrnm id,将 id 值传递为

var username=document.getElementById('usrnm').value;
var password=document.getElementById('pass').value;

或者

否则通过 if 条件为

if(username.value == "abc"){
    if(password.value == "123"){
      .....
    }
}
于 2013-08-08T12:07:57.480 回答
0

更改代码

var username=document.getElementById('usrnm').value;

var password=document.getElementById('pass').value;

于 2013-08-08T12:10:26.973 回答