gpt4 book ai didi

javascript - 如何显示我的 JavaScript 计数器?

转载 作者:行者123 更新时间:2023-12-03 05:44:52 24 4
gpt4 key购买 nike

我有一个很棒的 JavaScript 计数器,它运行得非常完美。唯一的问题是,只有先单击按钮,才会显示实际信息。但我希望计数器和其他文本在单击按钮时不断显示和更新。

我在这里缺少什么?

JavaScript:

<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "" + localStorage.clickcount + " <br>Subscribers So Far! And...<br>" + (1500 - +localStorage.clickcount) + "<br>Subscribers To Go" ;
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>

HTML:

<p><button onclick="clickCounter()" id="paypal-btn1" type="button">Click me!</button></p>
<p><button onclick="clickCounter()" id="paypal-btn2" type="button">Click me!</button></p>
<p><button onclick="clickCounter()" id="paypal-btn3" type="button">Click me!</button></p>
<div id="result"></div>

最佳答案

看看这个。创建另一个函数来显示信息,然后在页面加载时调用它。然后当单击按钮时计数器增加时再次调用此函数。

<script>
displayInformation();
function displayInformation() {
document.getElementById("result").innerHTML = "" + localStorage.clickcount + " <br>Subscribers So Far! And...<br>" + (1500 - +localStorage.clickcount) + "<br>Subscribers To Go" ;
}
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
displayInformation();/*Call this to refresh the click information*/
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
</script>

参见此处jsfiddle

关于javascript - 如何显示我的 JavaScript 计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com