以html / js投票计数器

时间:2016-10-30 21:14:19

标签: javascript html forms button

我对编程很新,并且一直在学习HTML,CSS和Javascript。我正在开展涉及即将到来的选举的项目,用户按下按钮(使用html中的<form>)来投票给候选人。我遇到的问题是转发结果。使用javascript或html,我如何能够跟踪按下每个按钮的次数,并在网页中稍后传递信息,其中显示每个候选人的投票数和总投票数。

编辑我已经把代码搞砸了一下,这是我当前的javascript文件,我设置程序告诉你在alert()消息中投票给谁,但是候选人的名字没有正确显示......

<!DOCTYPE html>
<html>     
<head>         
<meta charset="utf-8" >         
<title>Election</title>
</head>
<body>   
<center>
<h1>2016 Presidential Election</h1>
<h2>Vote Here</h2>
<form>
<button type="button" onclick="clicksubmit()">Click to vote for Trump</button>
<button type="button" onclick="clicksubmit()">Click to vote for Hillary</button>
</form>
<h3>Results:</h3>
</center>
<script src="election.js" type="text/javascript"></script>
</body> 
</html>

JS:

function clicksubmit(){

    var votehillary = document.getElementById('hillary'); 
    alert("You voted for "+ votehillary);
    var votetrump = document.getElementById('trump'); 
    alert("You voted for "+ votetrump);

}

1 个答案:

答案 0 :(得分:0)

要计算您的按钮点击次数,您可以为每个候选人声明一个变量,并在每次点击时递增它们。为此,您需要更改按钮元素和结果标题:

<h3 id="results">
  total: 0
  trump: 0
  hillary: 0
</h3>
<button type="button" id="trump-button">Click to vote for Trump</button>
<button type="button" id="hillary-button">Click to vote for Hillary</button>

在你的election.js文件中,你可以获取每个按钮并对它们应用onClick事件,增加页面加载时声明的变量:

var trump = 0;
var hillary = 0;

function refreshResults () {
  var results = document.getElementById('results');
  results.innerHTML = 'total: ' + (trump + hillary);
  results.innerHTML += '<br />trump: ' + trump;
  results.innerHTML += '<br />hillary: ' + hillary;
}

document.getElementById('trump-button').addEventListener('click', function () {
  trump++;
  refreshResults();
});

document.getElementById('hillary-button').addEventListener('click', function () {
  hillary++;
  refreshResults();
});