我有三个输入来收集候选人的名字然后当你按下计算时,它会将信息放在候选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;
//
答案 0 :(得分: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 id="btn" type="button">Calculate</button>
JS
addEventListener是通过onclick调用函数的好方法。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;
}
}