html投票并显示结果代码
时间: 2023-11-15 18:02:50 浏览: 151
HTML投票并显示结果的代码如下:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>投票</title>
</head>
<body>
<h1>你最喜欢的水果是:</h1>
<form id="voteForm">
<input type="radio" name="fruit" value="apple">苹果<br>
<input type="radio" name="fruit" value="banana">香蕉<br>
<input type="radio" name="fruit" value="orange">橙子<br>
<input type="radio" name="fruit" value="strawberry">草莓<br>
<input type="button" value="投票" onclick="vote()">
</form>
<div id="result">
<h2>投票结果:</h2>
<p id="appleVotes">苹果:0</p>
<p id="bananaVotes">香蕉:0</p>
<p id="orangeVotes">橙子:0</p>
<p id="strawberryVotes">草莓:0</p>
</div>
<script>
function vote() {
var selectedFruit = document.querySelector('input[name="fruit"]:checked').value;
var fruitVotes = localStorage.getItem(selectedFruit);
if (fruitVotes) {
fruitVotes = parseInt(fruitVotes) + 1;
} else {
fruitVotes = 1;
}
localStorage.setItem(selectedFruit, fruitVotes);
document.getElementById(selectedFruit + "Votes").innerText = selectedFruit + ":" + fruitVotes;
}
// 页面加载时显示之前的投票结果
window.onload = function() {
document.getElementById("appleVotes").innerText = "苹果:" + (localStorage.getItem("apple") || 0);
document.getElementById("bananaVotes").innerText = "香蕉:" + (localStorage.getItem("banana") || 0);
document.getElementById("orangeVotes").innerText = "橙子:" + (localStorage.getItem("orange") || 0);
document.getElementById("strawberryVotes").innerText = "草莓:" + (localStorage.getItem("strawberry") || 0);
};
</script>
</body>
</html>
```
这段代码会在页面上展示一个投票表单,用户可以选择自己最喜欢的水果进行投票,点击投票按钮后将向localStorage中存储投票结果,并在页面上实时展示投票结果。
阅读全文