使用滑块值动态更新JavaScript中的条形图
问题描述:
我正在尝试创建一个动态响应滑块输入的条形图。使用滑块值动态更新JavaScript中的条形图
(1)我想访问外部脚本中的滑块值。目前,我试图通过定义一个使用document.getElementById()。value的函数来做到这一点。当我运行alert来检查这个值是否被存储时,我得到了undefined。这里发生了什么?
(1b)在将代码复制到plunker中时,它会显示“意外的开始标记”,并将其忽略。这是为什么发生? (2)给定当前的代码,我想取滑块值,乘以已知常数,然后按这些输出排序条形图。做这种事情最好的办法是什么?
代码附此:https://plnkr.co/edit/C0iV74mBkFbFM0BVG7Ax?p=streamer
<script>
...
var test;
function kk()
{
test = document.getElementById('cardiovascular').value;
alert(test)
}
...
</script>
<h4> Cardiovascular Mortality </h4>
<div id="cardiovascular"></div>
<body onload="onload();">
<input type="button" value="click" onclick="kk();"/>
</body>
答
几个问题。根据w3schools,value属性设置或返回选项(表单提交时要发送到服务器的值)的值。你的id被分配给输入的父div。
假设你知道我要做的事情的数量,我沿着这个快速codepen的行。
作为一般的编码技巧,不是通过尝试立即做所有事情来使代码复杂化,而是将您的任务分解为更小更易于管理的块。这样,通过排序和调试代码就容易多了。它也可能有助于你的随机错误。
根据他们的价值订购你的酒吧,编号点击这篇文章here虽然我会说这样的事情是更容易使用jQuery,如果可能的话。你可以看看这个here的例子。
祝你好运,如果它回答你的问题,请不要忘记提高答案。
<p>value for chart 1</p>
<input id="value_for_chart1" type="text" value="3"/>
<p>value for chart 2</p>
<input id="value_for_chart2" type="text" value="3"/>
<input id="trigger_button" type="button" value="click" onclick="kk()"/>
<div class="bar-container">
<div id="bar-two" value=""></div>
<div id="bar-one" value=""></div>
</div>
#bar-one {
width: 0px;
height: 50px;
background-color: red;
}
#bar-two {
width: 0px;
height: 50px;
background-color: green;
}
function kk() {
var chart1value;
var chart2value;
var fixedValue = 100; //or whatever your fixed value is
var barWidth1 = document.querySelector("#bar-one");
var barWidth2 = document.querySelector("#bar-two");
//Return value of input. We use parseInt here to convert the string"value" to the integer value
chart1value = parseInt(document.getElementById('value_for_chart1').value);
chart2value = parseInt(document.getElementById('value_for_chart2').value);
chart1value = chart1value * fixedValue;
chart2value = chart2value * fixedValue;
//assign value to bar chart item, you can grab this value later for sorting
document.getElementById('bar-one').value=chart1value;
document.getElementById('bar-two').value=chart2value;
//set the css width property of the bar to its value
barWidth1.style.width = chart1value + "px";
barWidth2.style.width = chart2value + "px";
}