我一直在制作简单的Javascript程序,我会为不同的网站为我的朋友运行,我一直在尝试使用按钮制作统治风格(使命召唤游戏模式)程序。我查看了一个网站,并尝试使用设置的间隔,但我无法弄清楚如何让按钮访问脚本。
这是我的代码:
<!DOCTYPE html>
<html>
<body>
<p id = "blue"></p>
<p id = "red"></p>
<button onclick="StartA()">Start for Red</button>
<button onclick="StopA()">Stop for red</button>
<button onclick="StartB()">Start for Blue</button>
<button onclick="StopB()">Stop for Blue</button>
<script>
var startRed;
var startBlue;
var r=1;
var b=1;
var startA = function(){
var startRed = setInterval(function(){redscore++};,3000)
};
var startB = function(){
var startBlue = setInterval(function(){bluescore++};,3000)
};
var StopA = function(){
clearInterval(startRed);
};
var StopB = function() {
clearInterval(startBlue);
};
document.getElementById("blue").innerHTML=bluescore;
document.getElementById("red").innerHTML=redscore;
</script>
</body>
</html>
答案 0 :(得分:6)
下面是应该按照您的意图运行的更新代码。把你的得分老师变成一个班级可能是值得的,因为他们是多余的。
<p id="blue"></p>
<p id="red"></p>
<button onclick="startA()">Start for Red</button>
<button onclick="stopA()">Stop for red</button>
<button onclick="startB()">Start for Blue</button>
<button onclick="stopB()">Stop for Blue</button>
var startRed;
var startBlue;
var bluescore = 1;
var redscore = 1;
function startA() {
stopA();
startRed = setInterval(function () {
redscore++;
updateUI();
}, 3000)
};
function startB() {
stopB();
startBlue = setInterval(function () {
bluescore++;
updateUI();
}, 3000)
};
function stopA() {
clearInterval(startRed);
};
function stopB() {
clearInterval(startBlue);
};
function updateUI() {
document.getElementById("blue").innerHTML = bluescore;
document.getElementById("red").innerHTML = redscore;
}
updateUI();
答案 1 :(得分:0)
您正在寻找以下代码。变化是:
startA() => StartA(), startB() => StartB()
等)<p>
元素在区间内更新(否则,它们永远不会更新)您可以在此处查看jsfiddle:http://jsfiddle.net/5tcNb/
<body>
<script>
var startRed, startBlue;
var redscore = 0, bluescore = 0;
var r = 1, b = 1;
function StartA() {
startRed = setInterval(function() {
redscore++;
document.getElementById("red").innerHTML = redscore;
}, 3000);
};
function StartB() {
startBlue = setInterval(function() {
bluescore++;
document.getElementById("blue").innerHTML = bluescore;
}, 3000);
};
function StopA() {
clearInterval(startRed);
};
function StopB() {
clearInterval(startBlue);
};
</script>
<p id="blue">0</p>
<p id="red">0</p>
<button onclick="StartA()">Start for Red</button>
<button onclick="StopA()">Stop for red</button>
<button onclick="StartB()">Start for Blue</button>
<button onclick="StopB()">Stop for Blue</button>
</body>