我正在尝试使用JavaScript制作HTML图表。 HTML页面应包含图表所属的div容器。
我想使用我主要的功能来做这件事; digram(uDivHTML,uList,uWidth)。第一个参数采用div内部html,如下面的代码所示,变量gram。
seccond参数应该采用数组。该数组应该有一个字符串,然后是一个数字,依此类推......
第三个参数应该使用一个用于乘以每个毛细管长度的数字。
为什么这不起作用?我一直在尝试不同的调试器,并多次查看它,但似乎无法找出原因。任何帮助表示赞赏;)
<head>
<title>Test</title>
<meta charset = "UTF-8">
</head>
<body>
<div id = "gram"></div>
<button id = "btn">123</button>
<script>
var gram = document.getElementById("gram").innerHTML;
var myList = [
"norge",20,
"svergie",17,
"danmark",23,
"england",11,
"usa",64
];
function diagram(uDivHTML, uList, uWidth) {
for(var index = 0, colIndex = 0; index < (uList.length - 1); index+=2, colIndex++) {
var col;
switch(colIndex) {
case 0: col = "red";
case 1: col = "blue";
case 2: col = "yellow";
case 3: col = "green";
case 4: col = "orange"; colIndex = 0;
}
var wid = uWidth * uList[index + 1];
uDivHTML +=
"<div style ='height:20px;display:block;color:white;background-color:"+col+";width:"+wid+"px;'>"+
uList[index]+"</div>";
}
}
var btn = document.getElementById("btn");
btn.onclick = diagram(gram, myList, 10);
</script>
</body>
答案 0 :(得分:1)
我无法看到你如何实际更新div#gram的内容。您必须将uDivHTML的结果分配给div的innerHTML。
答案 1 :(得分:1)
您的代码存在一些问题,
我已经修改了一些代码以使其正常工作。
window.onload = function() {
var gram = document.getElementById("gram");
var myList = [
"norge", 20,
"svergie", 17,
"danmark", 23,
"england", 11,
"usa", 64
];
function diagram(uDivHTML, uList, uWidth) {
for (var index = 0, colIndex = 0; index < (uList.length - 1); index += 2, colIndex++) {
var col;
switch (colIndex) {
case 0:
col = "red";
break;
case 1:
col = "blue";
break;
case 2:
col = "yellow";
break;
case 3:
col = "green";
break;
case 4:
col = "orange";
colIndex = 0;
break;
}
var wid = uWidth * uList[index + 1];
uDivHTML.innerHTML +=
"<div style ='height:20px;display:block;color:white;background-color:" + col + ";width:" + wid + "px;'>" +
uList[index] + "</div>";
}
}
var btn = document.getElementById("btn");
btn.onclick = function() {
diagram(gram, myList, 10);
}
}
&#13;
<div id="gram"></div>
<button id="btn">123</button>
&#13;