Javascript 生成的表不起作用

标签 javascript html arrays for-loop html-table

谁能发现明显的错误?为什么这个 Javascript 生成的表(showResults 函数)没有出现在我的 html 中?当我有很多文字值要引用时,这总是会发生......我也很感激对我的格式(空白)的任何其他评论!

   <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>");
    }

最佳答案

我认为你需要在与字符串进行比较时给出引号,因此 D 与“D”不同。

  switch (partyType){
            case "D":  barText="<td class='dem'></td>";
            break;
            case "R":  barText="<td class='rep'></td>";
            .......

也正如其他人所建议的那样,在调用函数时删除函数关键字。

var totalV = function totalVotes(votes);

应该是

  var totalV = totalVotes(votes);

关于Javascript 生成的表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17190391/

相关文章:

javascript - 如何使这个 slider 工作?

Javascript - 如何更改对象属性而不重新分配它们

javascript - Html 列表项在悬停时保持事件状态

ios - 在indexpath.row之后快速追加到数组

java - 在 Java 2D ArrayList 中转置值

java - 如何使用字符串从数组列表中获取数据

javascript图像加载有0宽度和0高度

javascript - 为什么我的 Mocha Reporter 会重复报告测试?

javascript - HTML 列表添加文本框

css - 自动调整 2 个 div 从列到行的大小,同时保持全宽