我正在尝试使用onclick事件为可变变量(运行记分卡)分配一个整数。
这个想法是,用户将点击一个按钮,并根据他们选择的按钮,onclick事件将使用值更新runningTally变量。
我的代码将值插入HTML页面,但它会自动插入所有可能值的总和,而不仅仅是onclick中的值。
我尝试过多种方式重写代码但没有成功。有人可以提供一些帮助吗?
var one = document.getElementById('1');
var two = document.getElementById('2');
var btn = document.getElementById('showtally');
let runningTally = 0;
function score(points) {
runningTally += points;
document.getElementById('showtally').innerHTML = runningTally;
};
one.onclick = score(5);
two.onclick = score(4);
答案 0 :(得分:0)
您可以像这样附加eventlisteners:
let runningTally = 0;
function score(points) {
runningTally += points;
document.getElementById('showtally').innerHTML = runningTally;
};

<button id="1" onclick="score(5)">1</button>
<button id="2" onclick="score(4)">2</button>
<div id="showtally"></div>
&#13;
答案 1 :(得分:0)
您可以像这样分配匿名函数
var one = document.getElementById('1');
var two = document.getElementById('2');
var btn = document.getElementById ('showtally');
let runningTally = 0;
function score(points) {
runningTally += points;
document.getElementById('showtally').innerHTML = runningTally;
};
one.onclick = function(){score(5);};
two.onclick = function(){score(4);};
<button id="1">1</button>
<button id="2">2</button>
<label id="showtally">0</div>