正如您在JSFiddle中看到的那样,登录和注册的切换工作正常,但是当我在本地计算机上测试时,它说" Uncaught TypeError:无法读取属性'的addEventListener' of null"对于bt2。
这是代码
CSS
#login
{
}
#register
{
display:none;
}
#container{
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
input, select {
padding: 9px;
border: solid 1px #E5E5E5;
outline: 0;
font: normal 13px/100% Verdana, Tahoma, sans-serif;
width: 200px;
background: #FFFFFF url('bg_form.png') left top repeat-x;
background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}
select {
width: auto;
}
input:hover, select:hover,
input:focus, select:focus {
border-color: #C9C9C9;
-webkit-box-shadow: rgba(0, 0, 0, 0.15) 0px 0px 8px;
}
input[type=submit] {
width: auto;
padding: 9px 15px;
background: #617798;
border: 0;
font-size: 14px;
color: #FFFFFF;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
HTML
<div id="container">
<button id="bt1" type="button"> Login
</button>
<button id="bt2" type="button">Register
</button>
<br>
<div id="login">
Login Form
</div>
<div id="register">
<form action="#" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Salutation
</td>
<td>
<select name="Salutation">
<option value="Ms">Ms</option>
<option value="Mrs">Mrs</option>
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
</select>
</td>
</tr>
<tr>
<td>
First Name
</td>
<td>
<input type="text" name="F_Name">
</td>
</tr>
<tr>
<td>
Last Name
</td>
<td>
<input type="text" name="L_Name">
</td>
</tr>
<tr>
<td>
E-Mail
</td>
<td>
<input type="text" name="email">
</td>
</tr>
<tr>
<td>
Password(Min 6 characters)
</td>
<td>
<input type="password" name="pass">
</td>
</tr>
<tr>
<td>
Phone Number(10 digit)
</td>
<td>
<input type="text" name="P_Number">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="Submit" value="Get Started" name="Submit">
</td>
</tr>
</table>
</form>
</div>
</div>
的Javascript
function swap(login, register) {
document.getElementById(login).style.display = 'block';
document.getElementById(register).style.display = 'none';
}
document.getElementById('bt1').addEventListener('click',function(e){
swap('login','register');
});
document.getElementById('bt2').addEventListener('click',function(e){
swap('register','login');
});
我已尽力了解这个问题背后的原因,但似乎我无法这样做。
任何帮助都将不胜感激。
答案 0 :(得分:3)
您正在HTML头中加载脚本,当时不存在任何DOM元素,导致在undefined上调用addEventListener方法,这会引发错误。
两种解决方案: