我正在尝试将登录凭据保存到HTML表中(请耐心等待,我不是专业人士)。我使用的是push方法来存储数据,但最终它仅存储上次迭代的数据,因为它是围绕click函数构建的。所以我的问题是我如何存储所有凭据,而不仅仅是最后一个凭据
<body>
<form name="login" class="diss">
Username<input type="text" name="userid" id="userName" />
Password<input type="password" name="pswrd" id="passw"/>
<input type="button" class="btn-dis" value="Login"/>
</form>
<table id="showAfter">
<tr>
<th>User Name</th>
<th>Password</th>
</tr>
</table>
<script src="firstMission.js"></script>
</body>
document.querySelector('.btn-dis').addEventListener('click', function()
x = document.getElementById("userName").value;
y = document.getElementById("passw").value;
table=document.getElementById('showAfter');
if (x=='' || y ==''){
alert("no can do");
restart();
}
else{
myTestArr.push([x,y]);
for(var i=0;i<myTestArr.length;i++)
{
var newRow = table.insertRow(table.length);
for(var j=0;j<myTestArr[i].length;j++)
{
var cell = newRow.insertCell(j);
cell.innerHTML=myTestArr[i][j];
}
}
}
mySecArr[i] = JSON.parse(JSON.stringify(myTestArr[i])); //copying to another
array
myTestArr.pop();
});
答案 0 :(得分:0)
我不确定您要在这里做什么。但是,根据我的想法,以下实现将允许您将新的用户名和密码添加到表中,同时将它们存储到数组中。
const credentials = [];
document.querySelector('.btn-dis').addEventListener('click', function(e) {
let user = document.querySelector("#userName").value,
pass = document.querySelector("#passw").value,
table = document.querySelector("#showAfter");
if (!user && !pass) {
alert("no can do")
} else {
credentials.push([user, pass]);
var newRow = table.insertRow(table.length);
var cell = newRow.insertCell(0);
cell.innerHTML = user;
cell = newRow.insertCell(1);
cell.innerHTML = pass;
}
})
<body>
<form name="login" class="diss">
Username<input type="text" name="userid" id="userName" /> Password
<input type="password" name="pswrd" id="passw" />
<input type="button" class="btn-dis" value="Login" />
</form>
<table id="showAfter">
<tr>
<th>User Name</th>
<th>Password</th>
</tr>
</table>
</body>
话虽如此,将凭据保存到内存通常是一种不好的做法,我不建议这样做。但是如果您是初学者,我将假设这仅用于学习目的。