【发布时间】:2013-06-15 22:30:02
【问题描述】:
谁能发现一个明显的错误?为什么这个 Javascript 生成的表(showResults 函数)没有出现在我的 html 中?当我有很多文字值要引用时,总是会发生这种情况......我也会感谢我的格式(空白)上的任何其他 cmets!
<script type="text/javascript">
//calculates sum of all values within an array
function totalVotes(votes){ /
var total=0;
for (i=0;i<votes.length;i++){
total = votes[i] + total;
}
return total;
}
//calculates a percentage, rounded to nearest integer
function calcPercent(item, sum){
return Math.round((item/sum)*100);
}
//tests value of partyType parameter
function createBar(partyType, percent){
switch (partyType){
case D: barText="<td class='dem'></td>";
break;
case R: barText="<td class='rep'></td>";
break;
case I: barText="<td class='ind'></td>";
break;
case G: barText="<td class='green'></td>";
break;
case L: barText="<td class='lib'></td>";
break;
}
for(i=1;i<=percent;i++){
document.write(barText);
}
}
function showResults(race,name,party,votes){
var totalV=function totalVotes(votes);
document.write("<h2>" +race+ "</h2>");
document.write("<table cellspacing='0'>");
document.write("<tr>");
document.write("<th>Candidate</th>");
document.write("<th class='num'> Votes</th>");
document.write("<th class='num'>%</th>");
document.write("</tr>");
for (r=0;r<name.length;r++){
document.write("<tr>");
document.write("<td>"+name[i]+ '(' +party[r]+ ")" +"</td>");
document.write("<td class='num'>" +votes[r]+ "</td>");
var percent=function calPercent(votes[r],totalV)
document.write("<td class='num'>(" +percent[r]+ "%)</td>");
createBar(party[r], percent);
document.write("</tr>");
}
document.write("</table>");
}
【问题讨论】:
-
很确定
var totalV=function totalVotes(votes);不是有效的 Javascript。我想你的意思是var totalV=totalVotes(votes);。 -
这也是无效的
for(i=1;i<=percent;i++),因为在document.write("<td class='num'>(" +percent[r]+ "%)</td>");中返回您的代码,我认为您的意思是写for(i=1;i<percent.length;i++)。对于你的 for 循环还有一点,在声明你迭代的变量时最好使用var,以便在循环之后处理它。
标签: javascript html arrays for-loop html-table