我有三个输入,将收集候选者的名称,然后按计算时,它将把信息放在底部的候选者div ID中。我已经注释掉了每个输入的JS,但是没有办法使用带有索引的函数来使代码更短吗?
这是一个jsfiddle。它不能在jQuery中,因为我们还没有学到。 https://jsfiddle.net/rtomino/oL3y9y4a/1/
<fieldset id="candidates">
<legend>Candidates</legend>
<div>
<label for="cand1">Candidate 1</label>
<input class="candidate" id="cand1" placeholder="Candidate"/>
</div>
<div>
<label for="cand2">Candidate 2</label>
<input class="candidate" id="cand2" placeholder="Candidate"/>
</div>
<div>
<label for="cand3">Candidate 3</label>
<input class="candidate" id="cand3" placeholder="Candidate"/>
</div>
</fieldset>
<fieldset id="statistics">
<legend>Current Results</legend>
<div>
Candidate 1
<div id="candidateName1"></div>
<label for="cand1pct">Percentage</label>
<output id="cand1pct"></output>
</div>
<div>
Candidate 2
<div id="candidateName2"></div>
<label for="cand2pct">Percentage</label>
<output id="cand2pct"></output>
</div>
<div>
Candidate 3
<div id="candidateName3"></div>
<label for="cand3pct">Percentage</label>
<output id="cand3pct"></output>
</div>
</fieldset>
<button onclick="calculateVotes()" type="button">Calculate</button>
// var cand1 = document.getElementById('cand1').value;
// document.getElementById('candidateName1').innerHTML = cand1;
//
// var cand2 = document.getElementById('cand2').value;
// document.getElementById('candidateName2').innerHTML = cand2;
//
// var cand3 = document.getElementById('cand3').value;
// document.getElementById('candidateName3').innerHTML = cand3;
//
最佳答案
<fieldset id="candidates">
<legend>Candidates</legend>
<div>
<label for="cand1">Candidate 1</label>
<input class="candidate" id="cand1" placeholder="Candidate" />
</div>
<div>
<label for="cand2">Candidate 2</label>
<input class="candidate" id="cand2" placeholder="Candidate" />
</div>
<div>
<label for="cand3">Candidate 3</label>
<input class="candidate" id="cand3" placeholder="Candidate" />
</div>
</fieldset>
<fieldset id="statistics">
<legend>Current Results</legend>
<div>
Candidate 1
<div id="candidateName1"></div>
<label for="cand1pct">Percentage</label>
<output id="cand1pct"></output>
</div>
<div>
Candidate 2
<div id="candidateName2"></div>
<label for="cand2pct">Percentage</label>
<output id="cand2pct"></output>
</div>
<div>
Candidate 3
<div id="candidateName3"></div>
<label for="cand3pct">Percentage</label>
<output id="cand3pct"></output>
</div>
</fieldset>
<button id="btn" type="button">Calculate</button>
JS
与通过onclick调用函数相比,addEventListener是一个很好的方法。see this
document.getElementById ("btn").addEventListener ("click", calculateVotes, false);
function calculateVotes() {
// For simplifying you can use a for loop
for(i=1;i<=3;i++)
{
name = document.getElementById('cand'+i).value;
document.getElementById('candidateName'+i).innerHTML =name;
}
}