因此,当我单击“显示注册的用户”按钮时,我能够检索存储在本地存储器中的本地数据。但是,再次单击该按钮时,它将追加并再次显示数据。我不确定应该对代码的哪一部分进行调整,如果可以的话,请提供帮助。
此代码位于用户填写其详细信息的页面中。
<script>
document.addEventListener("DOMContentLoaded",docIsReady);
var signupboys;
function docIsReady(){
signupboys=localStorage.getItem("signupboys");
if (signupboys==null){
signupboys=[];
}
else {
signupboys=JSON.parse(signupboys);
}
document.getElementById("list").addEventListener("click",function(){
this.style.display="none";
});
}
function addToBook(){
var name=document.getElementById("name").value;
if (!checkExisting(name)){
var contact=document.getElementById("contact").value;
var obj={"name":name,"contact":contact};
var email=document.getElementById("email").value;
var obj={"name":name,"contact":contact,"email":email};
signupboys.push(obj);
localStorage.setItem("signupboys",JSON.stringify(signupboys));
alert("Thank you for signing up!");
}
displayAll();
document.getElementById("name").value="";
document.getElementById("contact").value="";
document.getElementById("email").value="";
document.getElementById("addBtn").disabled="true";
}
function checkExisting(name){
var existing=false;
for (i=0; i<signupboys.length; i++){
var obj=signupboys[i];
if (obj.name==name){
existing=true;
break;
}
}
if (existing){
document.getElementById("addBtn").disabled="true";
}
else {
document.getElementById("addBtn").disabled="";
}
return existing;
}
</script>
这是管理页面的代码,如果我连续单击“显示已注册的用户”,则会重复检索到的数据。
<script>
document.addEventListener("DOMContentLoaded",docIsReady);
var signupboys;
function docIsReady(){
signupboys=localStorage.getItem("signupboys");
if (signupboys==null){
signupboys=[];
}
else {
signupboys=JSON.parse(signupboys);
}
}
function displayAll(){
var rows=document.querySelectorAll("#regtable tre");
for (var r of rows){
r.parentNode.removeChild(r);
}
<!-- signupboys.sort(function(obj1,obj2){ --> // To sort the data in order
<!-- if (obj1.name.toUpperCase()>obj2.name.toUpperCase()) -->
<!-- return 1; -->
<!-- else if (obj1.name.toUpperCase()<obj2.name.toUpperCase()) -->
<!-- return -1; -->
<!-- else -->
<!-- return 0; -->
<!-- }); -->
for (i=0; i<signupboys.length; i++){
console.log(i+" --"+signupboys[i])
var table=document.getElementById("regtable");
var row = table.insertRow();
var fullname = row.insertCell(0);
var contact = row.insertCell(1);
var email = row.insertCell(2);
fullname.innerHTML = signupboys[i].name;
contact.innerHTML = signupboys[i].contact;
email.innerHTML = signupboys[i].email;
}
}