我写了一个函数,其中A和B是1到6之间的随机数。我希望A和B的结果显示在Counter中并保存,所以当我再次单击add me按钮时,它会添加结果a和b到最后的结果。
因此,如果我点击一次,而计数器显示10.我下次点击时,我得到8的结果。我希望计数器继续将结果添加到一起。
这是我的代码
<!DOCTYPE html>
<html>
<head>
<title>Javascript Counter</title>
<meta charset="utf-8">
<style type="text/css">
.container {text-align: center; font-size: 20px;}
</style>
</head>
<body>
<div class="container">
<p>The Counter = <span id="Count"> --- </span></p>
<p>A = <span id="a1">?</span></p>
<p>B = <span id="b1">?</span></p>
<input type="submit" value="Add Me" onclick="addTogether()" />
</div>
<script type="text/javascript">
function addTogether(){
var a1 = document.getElementById('a1');
var b1 = document.getElementById('b1');
var count = document.getElementById('Count');
var a = Math.floor(Math.random() * 6 + 1);
var b = Math.floor(Math.random() * 6 + 1);
var y = a + b ;
a1.innerHTML = a;
b1.innerHTML = b;
count.innerHTML = y;
}
</script>
</body>
</html>
答案 0 :(得分:2)
如果我理解正确的话。您只需将count
添加到y
值即可。
y + (parseInt(count.innerHTML, 10)||0)
如果您想要通过刷新保存它,那么您需要坚持到本地存储或其他东西。
<!DOCTYPE html>
<html>
<head>
<title>Javascript Counter</title>
<meta charset="utf-8">
<style type="text/css">
.container {text-align: center; font-size: 20px;}
</style>
</head>
<body>
<div class="container">
<p>The Counter = <span id="Count"> --- </span></p>
<p>A = <span id="a1">?</span></p>
<p>B = <span id="b1">?</span></p>
<input type="submit" value="Add Me" onclick="addTogether()" />
</div>
<script type="text/javascript">
function addTogether(){
var a1 = document.getElementById('a1');
var b1 = document.getElementById('b1');
var count = document.getElementById('Count');
var a = Math.floor(Math.random() * 6 + 1);
var b = Math.floor(Math.random() * 6 + 1);
var y = a + b ;
a1.innerHTML = a;
b1.innerHTML = b;
count.innerHTML = y + (parseInt(count.innerHTML, 10)||0);
}
</script>
</body>
</html>
&#13;
答案 1 :(得分:0)
或者......您可以将值存储在全局变量中。函数中的所有变量都是该函数的本地变量。另一种解决方案是:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Counter</title>
<meta charset="utf-8">
<style type="text/css">
.container {text-align: center; font-size: 20px;}
</style>
</head>
<body>
<div class="container">
<p>The Counter = <span id="Count"> --- </span></p>
<p>A = <span id="a1">?</span></p>
<p>B = <span id="b1">?</span></p>
<input type="submit" value="Add Me" onclick="addTogether()" />
</div>
<script type="text/javascript">
var counter = 0;
function addTogether(){
var a1 = document.getElementById('a1');
var b1 = document.getElementById('b1');
var count = document.getElementById('Count');
var a = Math.floor(Math.random() * 6 + 1);
var b = Math.floor(Math.random() * 6 + 1);
counter = a + b + counter ;
a1.innerHTML = a;
b1.innerHTML = b;
count.innerHTML = counter;
}
</script>
</body>
</html>
(我确信它也可以使用像闭包那样的发烧友技术......)