如何在使用JS的倒计时器中,结合用户输入,使用本地存储?

huangapple go评论83阅读模式
英文:

how do i use localstorage on a countdown timer with user input using JS

问题

我创建了下面的代码来制作一个倒计时器,它使用用户输入。

这段代码有两个页面,一个页面显示倒计时(首页),另一个页面用户输入详细信息(详细信息页)。

尽管代码能够运行,但主要问题是详细信息页面显示一个在每个间隔更新的错误。

如何在使用JS的倒计时器中,结合用户输入,使用本地存储?

我应该怎么做才能去掉这个错误?我已经花了一周的时间试图解决它。我做错了什么?

我的代码

首页:

<body>
    <div class="menu-button" id="menu-button">
        <div class="bar"></div>
    </div>
    <div class="container">
        <div class="timer-displaybox">
            <div class="box">
                <p class="big-text" id="days-display">00</p>
                <p class="time">days</p>
            </div>
            <div class="box">
                <p class="big-text" id="hours-display">00</p>
                <p class="time">hours</p>
            </div>
            <div class="box">
                <p class="big-text" id="mins-display">00</p>
                <p class="time">mins</p>
            </div>
            <div class="box">
                <p class="big-text" id="secs-display">00</p>
                <p class="time">secs</p>
            </div>
        </div>
        <div class="text-container">直到大日子</div> 
        <div class="index-button">
            <a href="details.html"><input type="text" value="点击这里开始"></a>
        </div>
    </div>
  </body>

详细信息页面:

<body> 
        <div class="details-box">
                <h2>输入您的详细信息</h2>
                    <div class="name">
                        <input type="email" id= "inputName" placeholder="Jane" autofocus  required>
                    </div>
                    <div class="date-box">
                        <input type="date" id="inputDate" placeholder="dd/mm/yyyy"  required >
                    </div>
                    <div class="message-box">
                        <textarea placeholder="您想显示的消息" id="inputMessage" 
cols="45" rows="8"></textarea>
                    </div>
            <div class="button-container">
                    <input type="button" class="button" value="提交" id="submit" disabled>
                    <span class="button" id="apply"><a href="index.html"><input type="button" value="应用" ></a></span>  
            </div>       
        </div>
        <div class="contact-menu">
            <div class="contact-heading">
                <h2>联系我</h2>
            </div>
            <div class="contact-icons">
                <a href=""><i class="fa fa-linkedin fa-g fa-xl" ></i></a> 
                <a href=""><i class="fa fa-github fa-g fa-xl"></i></a> 
                <a href=""><i class="fa fa-twitter fa-g fa-xl"></i></a> 
                <a href=""><i class="fa fa-envelope fa-g fa-xl"></i></a> 
            </div> 
        </div>  
    </body>

使用的JavaScript:

document.addEventListener('DOMContentLoaded',()=>{
   
   const nameFromUser = document.getElementById('inputName')
   const dateFromUser=document.getElementById('inputDate')
   const messageFromUser =document.getElementById('inputMessage')
   const submitBtn = document.getElementById('submit')
   const sec = 1000
   const min = sec*60
   const hour = min*60
   const day = hour*24

window.addEventListener('input',()=>{
     if (nameFromUser.value && messageFromUser.value.length>2 && dateFromUser.value) {
        localStorage.setItem('dateInput',dateFromUser.value)
        localStorage.setItem('nameInput',nameFromUser.value)
        localStorage.setItem('messageInput',messageFromUser.value) 
        submitBtn.removeAttribute('disabled')  
     }
    })

    let timerId
    function countDown() {   
      const specialDay = new Date(localStorage.getItem('dateInput

<details>
<summary>英文:</summary>

I created the code below for a countdowntimer which uses user input.

The code has 2 pages one page displays the count down (index page) and in the other page user enters details (details page).

Although the code runs, the main problem is that details page displays an error which updates every interval as shown.

![[details pg](https://i.stack.imgur.com/dHyZV.png)](https://i.stack.imgur.com/dHyZV.png).

What can i do to remove the error? I have spent a week trying to figure out. What I am doing wrong?

### My code

***Index Page:***

```html
&lt;body&gt;
    &lt;div class=&quot;menu-button&quot; id=&quot;menu-button&quot;&gt;
        &lt;div class=&quot;bar&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;div class=&quot;timer-displaybox&quot;&gt;
            &lt;div class=&quot;box&quot;&gt;
                &lt;p class=&quot;big-text&quot; id=&quot;days-display&quot;&gt;00&lt;/p&gt;
                &lt;p class=&quot;time&quot;&gt;days&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class=&quot;box&quot;&gt;
                &lt;p class=&quot;big-text&quot; id=&quot;hours-display&quot;&gt;00&lt;/p&gt;
                &lt;p class=&quot;time&quot;&gt;hours&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class=&quot;box&quot;&gt;
                &lt;p class=&quot;big-text&quot; id=&quot;mins-display&quot;&gt;00&lt;/p&gt;
                &lt;p class=&quot;time&quot;&gt;mins&lt;/p&gt;
            &lt;/div&gt;
            &lt;div class=&quot;box&quot;&gt;
                &lt;p class=&quot;big-text&quot; id=&quot;secs-display&quot;&gt;00&lt;/p&gt;
                &lt;p class=&quot;time&quot;&gt;secs&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;text-container&quot;&gt;Until the big day&lt;/div&gt; 
        &lt;div class=&quot;index-button&quot;&gt;
            &lt;a href=&quot;details.html&quot;&gt;&lt;input type=&quot;text&quot; value=&quot;Click here to start&quot;&gt;&lt;/a&gt;
        &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;

Details Page:

&lt;body&gt; 
        &lt;div class=&quot;details-box&quot;&gt;
                &lt;h2&gt;Enter Your Details&lt;/h2&gt;
                    &lt;div class=&quot;name&quot;&gt;
                        &lt;input type=&quot;email&quot; id= &quot;inputName&quot; placeholder=&quot;Jane&quot; autofocus  required&gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;date-box&quot;&gt;
                        &lt;input type=&quot;date&quot; id=&quot;inputDate&quot; placeholder=&quot;dd/mm/yyyy&quot;  required &gt;
                    &lt;/div&gt;
                    &lt;div class=&quot;message-box&quot;&gt;
                        &lt;textarea placeholder=&quot;Message you want displayed&quot; id=&quot;inputMessage&quot; 
cols=&quot;45&quot; rows=&quot;8&quot;&gt;&lt;/textarea&gt;
                    &lt;/div&gt;
            &lt;div class=&quot;button-container&quot;&gt;
                    &lt;input type=&quot;button&quot; class=&quot;button&quot; value=&quot;Submit&quot; id=&quot;submit&quot; disabled&gt;
                    &lt;span class=&quot;button&quot; id=&quot;apply&quot;&gt;&lt;a href=&quot;index.html&quot;&gt;&lt;input type=&quot;button&quot; value=&quot;Apply&quot; &gt;&lt;/a&gt;&lt;/span&gt;  
            &lt;/div&gt;       
        &lt;/div&gt;
        &lt;div class=&quot;contact-menu&quot;&gt;
            &lt;div class=&quot;contact-heading&quot;&gt;
                &lt;h2&gt;Contact Me&lt;/h2&gt;
            &lt;/div&gt;
            &lt;div class=&quot;contact-icons&quot;&gt;
                &lt;a href=&quot;&quot;&gt;&lt;i class=&quot;fa fa-linkedin fa-g fa-xl&quot; &gt;&lt;/i&gt;&lt;/a&gt; 
                &lt;a href=&quot;&quot;&gt;&lt;i class=&quot;fa fa-github fa-g fa-xl&quot;&gt;&lt;/i&gt;&lt;/a&gt; 
                &lt;a href=&quot;&quot;&gt;&lt;i class=&quot;fa fa-twitter fa-g fa-xl&quot;&gt;&lt;/i&gt;&lt;/a&gt; 
                &lt;a href=&quot;&quot;&gt;&lt;i class=&quot;fa fa-envelope fa-g fa-xl&quot;&gt;&lt;/i&gt;&lt;/a&gt; 
            &lt;/div&gt; 
        &lt;/div&gt;  
    &lt;/body&gt;

Javascript Used:

document.addEventListener(&#39;DOMContentLoaded&#39;,()=&gt;{
   
   const nameFromUser = document.getElementById(&#39;inputName&#39;)
   const dateFromUser=document.getElementById(&#39;inputDate&#39;)
   const messageFromUser =document.getElementById(&#39;inputMessage&#39;)
   const submitBtn = document.getElementById(&#39;submit&#39;)
   const sec = 1000
   const min = sec*60
   const hour = min*60
   const day = hour*24

window.addEventListener(&#39;input&#39;,()=&gt;{
     if (nameFromUser.value &amp;&amp; messageFromUser.value.length&gt;2 &amp;&amp; dateFromUser.value) {
        localStorage.setItem(&#39;dateInput&#39;,dateFromUser.value)
        localStorage.setItem(&#39;nameInput&#39;,nameFromUser.value)
        localStorage.setItem(&#39;messageInput&#39;,messageFromUser.value) 
        submitBtn.removeAttribute(&#39;disabled&#39;)  
     }
    })

    let timerId
    function countDown() {   
      const specialDay = new Date(localStorage.getItem(&#39;dateInput&#39;))
      const messageDisplay= document.querySelector(&#39;.text-container&#39;)
      const timerDisplay = document.querySelector(&#39;.timer-displaybox&#39;)
      const today = new Date()
      const timeDiff = specialDay-today
        
        if (timeDiff &lt;= -day) {
            timerDisplay.classList.add(&#39;timerUpgrade&#39;)
            timerDisplay.innerHTML=localStorage.getItem(&#39;nameInput&#39;)
            messageDisplay.innerHTML=&#39;I hope you had a wonderfull day!!!&#39; 
            clearInterval(timerId)
            return  
        }
        if (timeDiff ==0) {
            timerDisplay.classList.add(&#39;timerUpgrade&#39;)
            timerDisplay.innerHTML= localStorage.getItem(&#39;nameInput&#39;)
            messageDisplay.innerHTML= localStorage.getItem(&#39;messageInput&#39;)
            clearInterval(timerId)
            return
        } 
        document.getElementById(&#39;days-display&#39;).innerHTML=Math.floor(timeDiff/day)
        document.getElementById(&#39;hours-display&#39;).innerHTML=Math.floor((timeDiff % day)/hour)
        document.getElementById(&#39;mins-display&#39;).innerHTML= Math.floor((timeDiff %  hour)/min) 
        document.getElementById(&#39;secs-display&#39;).innerHTML=Math.floor((timeDiff % min) /sec)    
     }
   timerId = setInterval(countDown,sec)
})

I have tried to introduce localstorage.clear() inside the countdown function but still the error is not fixed.

答案1

得分: 2

从您的截图来看,它是用于带有details pg注释的HTML片段。假设您正在加载带有js page注释的JavaScript代码与此HTML一起,那么错误是因为在此行:

const timerDisplay = document.querySelector('.timer-displaybox')

details pg上没有一个具有timer-displaybox类的元素,因此timerDisplay变量将为null。然后,在if块中,对于以下行:

timerDisplay.innerHTML=localStorage.getItem('nameInput')

timerDisplaynull,因此将按照您的原始截图抛出错误。

为了纠正这个问题,您应该考虑将JavaScript拆分,以便仅加载与相关页面相关的代码。换句话说,countdown()函数代码和相关代码似乎只应包含在index pg HTML中,而不是details pg代码中。

英文:

It seems from your screenshot that it is for the HTML snippet annotated with details pg. Assuming you are loading the JavaScript code annotated as js page with this HTML, then the error is caused because in this line:

const timerDisplay = document.querySelector(&#39;.timer-displaybox&#39;)

There is no element on details pg that has a class of timer-displaybox, so the timerDisplay variable would be null. Then in the if blocks, for the following line:

timerDisplay.innerHTML=localStorage.getItem(&#39;nameInput&#39;)

timerDisplay is null and thus the error would be thrown as per your original screenshot.

To rectify this, you should consider splitting up your JavaScript such that only the relevant code is loaded for the relevant page. In otherwords, the countdown() function code and reletated code looks like it should only be included with the index pg HTML and not the details pg code.

答案2

得分: 0

这段代码存在许多问题。以下是一些需要考虑的事项:

  1. 错误发生是因为 timerDisplay 为 null。你的 localStorage 没有问题。

  2. 你在 countDown 函数内部使用了 setInterval,这意味着它会创建无数个同时运行的循环。将其改为 setTimeout,或者将 setInterval 移出函数外部。

  3. 你在 if 语句内部有很多重复的代码。如果你希望无论如何都执行它,可以将所有这些代码移出 if 语句。

  4. 在更改 innerHtml 之前,你可以添加一个 if(timerDisplay)。这不会解决你的问题,但会消除错误并有助于调试代码。

也许像下面这样的代码会更有帮助:

function countDown(specialDay) {   
  const today = new Date()
  const timeDiff = specialDay - today;
  document.getElementById('days-display').innerHTML = Math.floor(timeDiff / day);
  document.getElementById('hours-display').innerHTML = Math.floor((timeDiff % day) / hour);
  document.getElementById('mins-display').innerHTML = Math.floor((timeDiff % hour) / min);
  document.getElementById('secs-display').innerHTML = Math.floor((timeDiff % min) / sec);

  const timerDisplay = document.querySelector('.timer-displaybox');
  if (timerDisplay)
    timerDisplay.innerHTML = localStorage.getItem('nameInput');

  if (timeDiff > 0) {
    setTimeout(() => {
      countDown(specialDay);
    }, 1000);
  } else {
    // 当计时器达到零时执行某些操作。
  }
}
英文:

this code has A LOT of problems. Here's a few things for you to consider:

  1. the error is happening because timerDisplay is null. nothing wrong with your localStorage.

  2. you are using setInterval inside your countDown function, which means it's going to create an infinite number of loops all running at once. change it to setTimeout, or move setInterval outside your function.

  3. You have a lot of duplicate code inside your if statements. Move all that outside if you want to execute it no matter what.

  4. You can add an if(timerDisplay) before changing the innerHtml. This will not fix your problem, but it will make the error go away and help you debug the code.

Maybe something more like this would help:

function countDown(specialDay) {   
const today = new Date()
const timeDiff = specialDay-today;
document.getElementById(&#39;days-display&#39;).innerHTML=Math.floor(timeDiff/day)
document.getElementById(&#39;hours-display&#39;).innerHTML=Math.floor((timeDiff % day)/hour)
document.getElementById(&#39;mins-display&#39;).innerHTML= Math.floor((timeDiff %  hour)/min) 
document.getElementById(&#39;secs-display&#39;).innerHTML=Math.floor((timeDiff % min) /sec)    
const timerDisplay = document.querySelector(&#39;.timer-displaybox&#39;);
if(timerDisplay)
timerDisplay.innerHTML=localStorage.getItem(&#39;nameInput&#39;);
if(timeDiff &gt; 0) {
setTimeout(() =&gt; {
countDown(specialDay);
}, 1000);
} else {
// do something when timer reaches zero.
}
}

huangapple
  • 本文由 发表于 2023年4月10日 22:49:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定