使用 JS 创建并保存新的 tr 元素

问题描述 投票:0回答:1

我对编码相当陌生,尤其是 JS。我正在构建一个程序,旨在计算输入并将结果(连同日期)放入表格中。每次有新输入时,表中都应该有一个新条目。每当重新加载页面时,都应该保存和检索表的数据。

我现在遇到的问题是只保存了第一个条目。必须保存表中的所有数据。有人有建议吗?谢谢。

这是我的代码:

// variables

const input = document.getElementById('input');

//buttons

const enter = document.getElementById('enter-value');
const log = document.getElementById("log-value");
const save = document.getElementById("save-value");
const done = document.getElementById("done-button");

//log areas

const itemHolder = document.getElementById('item-holder');
const totalMarker = document.getElementById("grand-total");

// messagges

const negativeValueMessage = document.getElementById('value-message-negative');
const positiveValueMessage = document.getElementById('value-message-positive');
const doneMessage = document.getElementById('done');

//other

const tool = document.getElementById('tool');
const date = new Date();

//input testing code

function checkInput (){
    input.addEventListener('input', function(){
        if(input.value < 0 ){
           negativeValueMessage.style.display = "block";
           positiveValueMessage.style.display = "none";
           enter.style.display = "block";
           enter.disabled = false;
           enter.style.opacity = "100%";
        }
        else if (input.value > 0) {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "block";
            enter.style.display = "block";
            enter.disabled = false;
            enter.style.opacity = "100%";
        }
        else {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "none";
            enter.disabled = true;
            if(enter.disabled){
                enter.style.opacity = '60%';
            }
        }
    });
}
checkInput();

// input reception

function useInput (){
    enter.addEventListener('click', function(){
        enter.style.display = 'none';
        log.style.display = 'block';
        inputDisalowed();
        log.addEventListener('click', function(){
            const addValues = Number(input.value) + Number(totalMarker.value);
            const total = addValues;
            totalMarker.value = total;
            function newInfo(){
                itemHolder.innerHTML += '<tr><td id="date">' + dateHolder + '</td><td id="amount">$' + totalMarker.value + '</td></tr>';
            }
            newInfo();
            log.style.display = 'none';
            save.style.display = 'block';
            save.addEventListener('click', function(){
                doneMessage.style.display = "grid";
                tool.style.display = 'none';
                const dateData = document.getElementById('date').innerText;
                const amountData = document.getElementById('amount').innerText;
                const dataArray = [dateData, amountData];
                localStorage.setItem('savedDate', (dataArray[0]));
                localStorage.setItem('savedAmount', dataArray[1]);
                localStorage.setItem('savedTotal', Number(totalMarker.value));
                done.addEventListener('click', function(){
                    reloadPage();
                });
            });
        });
    });
}
useInput();
retrieveOnReload();
const dateHolder = monthFixedValue() + '/' + date.getDate() + '/' + date.getFullYear();

function monthFixedValue (){
    return date.getMonth() + 1;
}
function inputDisalowed (){
    input.addEventListener('input', function(){
        alert("You have already input your value. Inputing again will always restart the proccess.");
        location.reload();
    });
}
function retrieveOnReload(){
    window.addEventListener('DOMContentLoaded', function(){
    const retrievedDate = localStorage.getItem('savedDate');
    const retrieveAmount = localStorage.getItem('savedAmount');
    itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate + '</td><td id="amount">' + retrieveAmount + '</td></tr>';});
    totalMarker.value = Number(localStorage.getItem('savedTotal'));
};
function reloadPage() {
    window.location.href = window.location.href;
}
*{
    box-sizing: border-box;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
::-webkit-scrollbar{
    width:13px;
}
::-webkit-scrollbar-track{
    background: rgb(160,180,190);
    border-radius: 5px;
}
::-webkit-scrollbar-thumb{
    background: rgb(120,140,150);
    border-radius: 10px;
}
body {
    background-image: url(/Background.svg);
    display: grid;
    width: 100vw;
    justify-content: center;
    margin: 0;
    background-position: center;
    align-content: center;
    justify-items: center;
}
h1{
    border: 1px solid black;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: linear-gradient(
        rgb(150,170,180),
        rgb(120,140,150)
    );
    border-radius: .5vw;
    margin-bottom: 10px;
    width: 80vw;
    height: 70px;
    min-width: 400px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    color: rgb(20,20,90);
    font-size: 40px;
    border: none;
    margin-top: -150px;
    margin-left: -20px;
}
main{
    display: grid;
    align-items: center;
    justify-items: center;
    background: linear-gradient(
        rgb(150,170,180) 20%,
        rgb(120,140,150) 
    );
    border-radius: .5vw;
    margin-top: 10px;
    padding: 20px;
    width: 80vw;
    min-width: 400px;;
}
.inputs {
    margin: 20px;
    width: 90%;
    display: flex;
    justify-content: center;
}
input {
    border: none;
    background-color: rgb(30,90,130);
    color: rgb(10,10,50);
    height: 35px;
    width: 220px;
    font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    font-size: 15px;
    border-bottom: 2px solid rgb(20,80,100);
    border-radius: .2vw;
    margin-right: 3px;
    &::placeholder{
        color: rgb(100,140,180);
        font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
        font-size: 15px;
        font-weight: 900;
    }
}
#enter-value, #save-value, #log-value{
    border: none;
    border-radius: .2vw;
    background: rgb(20,80,180);
    font-size: 20px;
    font-weight: bolder;
    color: rgb(10,10,50);
    margin-left: 3px;
    &:hover{
        background: rgb(10,70,170);
    }
    &:active{
        background: rgb(20,80,180);
    }
}
#enter-value{
    display: none;
}
#save-value{
    display: none;
}
#log-value{
    display: none;
}
.value-message{
    color: rgb(30,40,100);
    display: none;
    margin-bottom: -20px;
}
label{
    text-align: center;
    font-weight: bolder;
    display: flex;
    align-items: baseline;
    font-size: 35px;
    
}
#grand-total{
    height: 40px;
    width: 150px;
    margin-bottom: 30px;
    margin-top: 0px;
    background: rgb(10,10,100);
    color: rgb(150,170,180);
    display: grid;
    align-content: center;
    text-align: center;
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
    border-radius: 2px;
    font-weight: bolder;
    font-size: 35px;
}
.table-window{
    height: 100px;
    width: 100%;
    display: grid;
    justify-items: center;
    align-items: center;
    overflow-y: scroll;
}
table{
    background-color: rgb(60,120,160);
    border-style: none;
    border-collapse: collapse;
}
.heading-row{
    background: rgb(100,160,200);
    height: 40px;
    width: 750px;
}
th{
    border: 0;
    width: 170px;
}
td{
    text-align: center;
    padding: 4px;
    width: 170px;
}
.th1,
.th2,
.th3{
    border-right: 2px solid rgb(170,170,255);
}
.td1,
.td2,
.td3{
    border-right: 2px solid rgb(170,170,255);
}
#done{
    position: absolute;
    display: grid;
    justify-items: center;
    display: none;
}
#done-img-holder{
    display: flex;
    justify-content: center;
    align-content: center;
    width: 100%;
    height: 100%;
}
#done-img-holder > img{
    width: 490px;
    display: grid;
    margin-top: -30px;
}
#done-info-holder{
    display: grid;
    justify-items: center;
    width: 400px;
    height: 170px;
    background: linear-gradient(
        rgb(180,180,190),
        rgb(140,140,150)
    );
    align-content: center;
    border-radius: .5vw;
}
#done-info-holder > p{
    font-size: 20px;
    color: rgb(10,70,160);
    font-weight: 900;
}
#done-info-holder > button{
    height: 50px;
    width: 130px;
    font-size: 30px;
    font-weight: 900;
    background: rgb(10,10,100);
    border: none;
    border-radius: 30px;
    color: rgb(120,140,150);
    &:hover{
        background: rgb(120,140,150);
        color: rgb(10,10,100);
    }
    &:active{
        background: rgb(10,10,100);
        color: rgb(120,140,150);
    }
}
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
    <main id="tool">
            <h1 class="heading">Simple Finance Tool</h1>
        <p id="value-message-negative" class="value-message">Your number is negative. This will be calculated as a financial loss.</p>
        <p id="value-message-positive" class="value-message">Your number is positive. This will be calculated as a financial gain.</p>
        <div class="inputs">
            <input type='number' id="input" class="input" placeholder="Input financial loss or gain." min="0"/>
            <button type="button" id="enter-value">Enter</button>
            <button type="button" id="log-value">Log Change</button>
            <button type="button" id="save-value">Save Change</button>
        </div>
        <label for="grand-total">$<input id="grand-total" disabled/></label>
        <div class="table-window">
            <table id="item-holder">
                <tr class="heading-row">
                    <th class="th1">Date</th>
                    <th class="th4">Total After Change</th>
                </tr>
            </table>
            
            
        </div>
        
    </main>
    <div id="done">
        <div id="done-img-holder">
            <img src="/Finance Tool/check-circle-svgrepo-com.svg"/>
        </div>
        <div id="done-info-holder">
            <p>All done! You're entry is complete.</p>
            <button id="done-button">Done</button>
        </div>
    </div>
    <script src="FinanceTool.js"></script>
</body>
</html>

这里还有 codePen 中代码的链接(注意:由于 codePen 的特殊性,代码在其中无法正常工作,但您可以将其从 codePen 复制到您的 IDE)。

codePenProjectLink

javascript html css local-storage
1个回答
0
投票

下面是一个入门指南,让您了解如果我正确理解了您的需求,我们可以如何继续。我制作了两种类型的数组,简单数组(dateArray 和 amountArray)和 dailyInputArray = 对象数组(dailyInput )。另请注意,为了更好、更安全的存储,您需要存储在 MySQL 数据库中。

let amountArray=[]
let dateArray=[]
let dailyInput={}
let dailyInputArray=[]
let retrieveDailyInputValues = localStorage.getItem('DailyInputValues');
retrieveDailyInputValues = JSON.parse(retrieveDailyInputValues)
console.log(retrieveDailyInputValues)
if(retrieveDailyInputValues && retrieveDailyInputValues.length!=0){
    dailyInputArray=retrieveDailyInputValues
}else{
    dailyInputArray=[]
}


const input = document.getElementById('input');

//buttons

const enter = document.getElementById('enter-value');
const log = document.getElementById("log-value");
const save = document.getElementById("save-value");
const done = document.getElementById("done-button");

//log areas

const itemHolder = document.getElementById('item-holder');
const earningHolder = document.getElementById('earning-holder');
const totalMarker = document.getElementById("grand-total");

// messagges

const negativeValueMessage = document.getElementById('value-message-negative');
const positiveValueMessage = document.getElementById('value-message-positive');
const doneMessage = document.getElementById('done');

//other

const tool = document.getElementById('tool');
const date = new Date();
const dateHolder = monthFixedValue() + '/' + date.getDate() + '/' + date.getFullYear();
function monthFixedValue (){
    return date.getMonth() + 1;
}


//input testing code

function checkInput (){
    input.addEventListener('input', function(){
        if(input.value < 0 ){
           negativeValueMessage.style.display = "block";
           positiveValueMessage.style.display = "none";
           enter.style.display = "block";
           enter.disabled = false;
           enter.style.opacity = "100%";
        }
        else if (input.value > 0) {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "block";
            enter.style.display = "block";
            enter.disabled = false;
            enter.style.opacity = "100%";
        }
        else {
            negativeValueMessage.style.display = "none";
            positiveValueMessage.style.display = "none";
            enter.disabled = true;
            if(enter.disabled){
                enter.style.opacity = '60%';
            }
        }
    });
}
checkInput();

// input reception

function useInput (){
    enter.addEventListener('click', function(){
        enter.style.display = 'none';
        log.style.display = 'block';
        inputDisalowed();
        log.addEventListener('click', function(){
            dailyInput.date = dateHolder
            dailyInput.earnings = input.value
            dailyInputArray.push(dailyInput)
            console.log(dailyInput)
            console.log(dailyInputArray)
            localStorage.setItem('DailyInputValues', JSON.stringify(dailyInputArray)); 
            const addValues = Number(input.value) + Number(totalMarker.value);
            const total = addValues;
            totalMarker.value = total;
            function newInfo(){
                itemHolder.innerHTML += '<tr><td id="date">' + dateHolder + '</td><td id="amount">$' + totalMarker.value + '</td></tr>';
            }
            newInfo();
            log.style.display = 'none';
            save.style.display = 'block';
            save.addEventListener('click', function(){
                doneMessage.style.display = "grid";
                tool.style.display = 'none';
                let dateData = document.getElementById('date').innerText; 
                let amountData = document.getElementById('amount').innerText; 
                dateArray.push(dateData) 
                amountArray.push(amountData) 
                localStorage.setItem('savedDate', JSON.stringify(dateArray)); 
                localStorage.setItem('savedAmount', JSON.stringify(amountArray)); 
                // const dataArray = [dateData, amountData];
                // localStorage.setItem('savedDate', (dataArray[0]));
                // localStorage.setItem('savedAmount', dataArray[1]);
                localStorage.setItem('savedTotal', Number(totalMarker.value));
                // done.addEventListener('click', function(){
                //     reloadPage();
                // });
            });
        });
    });
}
useInput();
retrieveOnReload();

function inputDisalowed (){
    input.addEventListener('input', function(){
        alert("You have already input your value. Inputing again will always restart the proccess.");
        location.reload();
    });
}
function retrieveOnReload(){
    window.addEventListener('DOMContentLoaded', function(){
        for(let i=0; i < dateArray.length ; i++){ 
            let retrievedDate = localStorage.getItem('dateArray'); 
            retrievedDate = JSON.parse(retrievedDate) 
            let retrieveAmount = localStorage.getItem('amountArray'); 
            retrieveAmount = JSON.parse(retrieveAmount)
            itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate[i] + '</td><td id="amount">' + retrieveAmount[i] + '</td></tr>';
         }

         for(let j=0; j < retrieveDailyInputValues.length ; j++){ 
            let retrieveEarningdDate = dailyInputArray[j].date 
            let retrieveDailyEarningd = dailyInputArray[j].earnings 
            earningHolder.innerHTML += '<tr><td id="date">' + retrieveEarningdDate + '</td><td id="amount">' + retrieveDailyEarningd + '</td></tr>';
         }
    // const retrievedDate = localStorage.getItem('savedDate');
    // const retrieveAmount = localStorage.getItem('savedAmount');
    // itemHolder.innerHTML += '<tr><td id="date">' + retrievedDate + '</td><td id="amount">' + retrieveAmount + '</td></tr>';
});
    totalMarker.value = Number(localStorage.getItem('savedTotal'));
};
function reloadPage() {
    window.location.href = window.location.href;
}
*{
  box-sizing: border-box;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
::-webkit-scrollbar{
  width:13px;
}
::-webkit-scrollbar-track{
  background: rgb(160,180,190);
  border-radius: 5px;
}
::-webkit-scrollbar-thumb{
  background: rgb(120,140,150);
  border-radius: 10px;
}
body {
  background-image: url(/Background.svg);
  display: grid;
  width: 100vw;
  justify-content: center;
  margin: 0;
  background-position: center;
  align-content: center;
  justify-items: center;
}
h1{
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(
      rgb(150,170,180),
      rgb(120,140,150)
  );
  border-radius: .5vw;
  margin-bottom: 10px;
  width: 80vw;
  height: 70px;
  min-width: 400px;
  font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  color: rgb(20,20,90);
  font-size: 40px;
  border: none;
  margin-top: -150px;
  margin-left: -20px;
}
main{
  display: grid;
  align-items: center;
  justify-items: center;
  background: linear-gradient(
      rgb(150,170,180) 20%,
      rgb(120,140,150) 
  );
  border-radius: .5vw;
  margin-top: 10px;
  padding: 20px;
  width: 80vw;
  min-width: 400px;;
}
.inputs {
  margin: 20px;
  width: 90%;
  display: flex;
  justify-content: center;
}
input {
  border: none;
  background-color: rgb(30,90,130);
  color: rgb(10,10,50);
  height: 35px;
  width: 220px;
  font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  font-size: 15px;
  border-bottom: 2px solid rgb(20,80,100);
  border-radius: .2vw;
  margin-right: 3px;
  &::placeholder{
      color: rgb(100,140,180);
      font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
      font-size: 15px;
      font-weight: 900;
  }
}
#enter-value, #save-value, #log-value{
  border: none;
  border-radius: .2vw;
  background: rgb(20,80,180);
  font-size: 20px;
  font-weight: bolder;
  color: rgb(10,10,50);
  margin-left: 3px;
  &:hover{
      background: rgb(10,70,170);
  }
  &:active{
      background: rgb(20,80,180);
  }
}
#enter-value{
  display: none;
}
#save-value{
  display: none;
}
#log-value{
  display: none;
}
.value-message{
  color: rgb(30,40,100);
  display: none;
  margin-bottom: -20px;
}
label{
  text-align: center;
  font-weight: bolder;
  display: flex;
  align-items: baseline;
  font-size: 35px;
  
}
#grand-total{
  height: 40px;
  width: 150px;
  margin-bottom: 30px;
  margin-top: 0px;
  background: rgb(10,10,100);
  color: rgb(150,170,180);
  display: grid;
  align-content: center;
  text-align: center;
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
  border-radius: 2px;
  font-weight: bolder;
  font-size: 35px;
}
.table-window{
  height: 100px;
  width: 100%;
  display: grid;
  justify-items: center;
  align-items: center;
  overflow-y: scroll;
}
table{
  background-color: rgb(60,120,160);
  border-style: none;
  border-collapse: collapse;
}
.heading-row{
  background: rgb(100,160,200);
  height: 40px;
  width: 750px;
}
th{
  border: 0;
  width: 170px;
}
td{
  text-align: center;
  padding: 4px;
  width: 170px;
}
.th1,
.th2,
.th3{
  border-right: 2px solid rgb(170,170,255);
}
.td1,
.td2,
.td3{
  border-right: 2px solid rgb(170,170,255);
}
#done{
  position: absolute;
  display: grid;
  justify-items: center;
  display: none;
}
#done-img-holder{
  display: flex;
  justify-content: center;
  align-content: center;
  width: 100%;
  height: 100%;
}
#done-img-holder > img{
  width: 490px;
  display: grid;
  margin-top: -30px;
}
#done-info-holder{
  display: grid;
  justify-items: center;
  width: 400px;
  height: 170px;
  background: linear-gradient(
      rgb(180,180,190),
      rgb(140,140,150)
  );
  align-content: center;
  border-radius: .5vw;
}
#done-info-holder > p{
  font-size: 20px;
  color: rgb(10,70,160);
  font-weight: 900;
}
#done-info-holder > button{
  height: 50px;
  width: 130px;
  font-size: 30px;
  font-weight: 900;
  background: rgb(10,10,100);
  border: none;
  border-radius: 30px;
  color: rgb(120,140,150);
  &:hover{
      background: rgb(120,140,150);
      color: rgb(10,10,100);
  }
  &:active{
      background: rgb(10,10,100);
      color: rgb(120,140,150);
  }
}
  <main id="tool">
    <h1 class="heading">Simple Finance Tool</h1>
<p id="value-message-negative" class="value-message">Your number is negative. This will be calculated as a financial loss.</p>
<p id="value-message-positive" class="value-message">Your number is positive. This will be calculated as a financial gain.</p>
<div class="inputs">
    <input type='number' id="input" class="input" placeholder="Input financial loss or gain." min="0"/>
    <button type="button" id="enter-value">Enter</button>
    <button type="button" id="log-value">Log Change</button>
    <button type="button" id="save-value">Save Change</button>
</div>
<label for="grand-total">$<input id="grand-total" disabled/></label>
<div class="table-window">
    <table id="item-holder">
        <tr class="heading-row">
            <th class="th1">Date</th>
            <th class="th4">Total After Change</th>
        </tr>
    </table>
    <table id="earning-holder">
      <tr class="heading-row">
          <th class="th1">Date</th>
          <th class="th4">Earning</th>
      </tr>
  </table>
    
</div>

</main>
<div id="done">
<div id="done-img-holder">
    <img src="/Finance Tool/check-circle-svgrepo-com.svg"/>
</div>
<div id="done-info-holder">
    <p>All done! You're entry is complete.</p>
    <button id="done-button">Done</button>
</div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.