[英]How can I make it so my var is changed to the same as the value in my dropdown menu?
I have some code which draws a parametrical circle and a var that dictates how many points it is made up of. 我有一些代码绘制一个参数化圆和一个变量,该变量决定了它由多少个点组成。 I can't figure out any way to change the var according to what option I pick in the dropdown menu.
我无法找到任何方法根据我在下拉菜单中选择的选项来更改var。
<!-- Dropdown -->
<select id="myList" onchange="PointsAmount()">
<option>2</option>
<option>4</option>
<option>8</option>
<option>16</option>
<option>32</option>
<option>64</option>
<option>128</option>
</select>
var points = 16;
var step = 2*Math.PI/points;
var h = 150;
var k = 150;
var r = 50;
function PointsAmount(){
var points = document.getElementById("myList").value;
}
//Circle draw
ctx.beginPath();
for(var theta=0; theta < 2*Math.PI; theta+=step){
var x = h + r*Math.cos(theta);
var y = k - r*Math.sin(theta);
ctx.lineTo(x,y);
}
ctx.closePath();
ctx.stroke();
You are using var points = document.getElementById("myList").value;
您正在使用
var points = document.getElementById("myList").value;
. 。 What you are doing is basically redefining
points
inside the function. 您要做的基本上是在函数内部重新定义
points
。 All you need to do is to remove the word var
from the start of the line and it will work as intended. 您需要做的就是从行首删除
var
一词,它将按预期工作。
var points = 16; var step = 2 * Math.PI / points; var h = 150; var k = 150; var r = 50; function PointsAmount() { points = document.getElementById("myList").value; console.log(points); }
<select id="myList" onchange="PointsAmount()"> <option>2</option> <option>4</option> <option>8</option> <option>16</option> <option>32</option> <option>64</option> <option>128</option> </select>
You can double check what you did before with calling a function to print the value of points every time the value is changing: 您可以通过调用函数在每次值更改时打印点的值来仔细检查之前所做的事情:
var points = 16; var step = 2 * Math.PI / points; var h = 150; var k = 150; var r = 50; function PointsAmount() { var points = document.getElementById("myList").value; console.log('inner var points=' + points); printPoints(); } function printPoints() { console.log('global var points=' + points); }
<!-- Dropdown --> <select id="myList" onchange="PointsAmount()"> <option>2</option> <option>4</option> <option>8</option> <option>16</option> <option>32</option> <option>64</option> <option>128</option> </select>
You can see that the global definition of points
is always 16, and that the inner function variable you defined there is changing, not effecting the global one. 您可以看到,
points
的全局定义始终为16,并且您在其中定义的内部函数变量正在更改,而不会影响全局变量。 That is the idea of scopes. 这就是范围的想法。 The
var points
exist only inside the scope of PointsAmount
but not out of it. PointsAmount
var points
仅存在于PointsAmount
范围内,但不存在于该范围PointsAmount
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.