我有一个具有三个按钮的JavaScript投票系统:
投票,清除和拒绝
当我单击“投票增加”按钮时,它保持为零。我必须按几次“投票”按钮才能投票。与否决相同。当我按清除时,它什么都不做。这是我所做的:
<button onclick="voteup()">
Vote Up
</button>
<button onclick="votedown()">
Vote Down
</button>
<button onclick="clear()">
Clear
</button>
<p Id="vote">
You have 0 votes
</p>
var a = 0;
function voteup() {
var b = a++;
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
function votedown(){
var b = a --;
document.getElementById('vote').innerHTML = "You have" + ' ' + b + "votes";
}
function clear() {
document.getElementById('vote').innerHTML = "Your votes has been cleared";
}
I set the variable out of the function so voteup and votedown functions can access the a variable. I can't understand this.
您的代码应为:
PS:似乎clear是保留字,我们不能将其用作函数名
var a = 0;
const pVote = document.getElementById('vote');
function voteup() {
pVote.textContent = "You have " + ++a + " votes";
}
function votedown(){
pVote.textContent = "You have " + --a + " votes";
}
function doClear() {
a = 0
pVote.textContent = "Your votes has been cleared";
}
<button onclick="voteup()"> Vote Up </button>
<button onclick="votedown()"> Vote Down </button>
<button onclick="doClear()"> Clear </button>
<p id="vote"> You have 0 votes </p>
我的方式...
const p_vote = document.getElementById('vote')
, btVote = document.getElementById('bt-vote')
var voteCount = 0
btVote.onclick = e =>
{
if (!e.target.matches('button[data-op]')) return
voteCount = eval(`${voteCount} ${e.target.dataset.op}`)
p_vote.textContent = voteCount ? `You have ${voteCount} votes` : 'Your votes has been cleared'
}
#VoteBtns button { width : 10em; }
<div id="bt-vote">
<button data-op="+ 1" > Vote Up </button>
<button data-op="- 1" > Vote Down </button>
<button data-op="* 0" > Clear </button>
</div>
<p Id="vote" > You have 0 votes </p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句