let form = document.getElementById("info");
var angle = Number(form.angle.value);
alert(angle);
var power = 0.01;
var canvas = document.getElementById("canvas");
var dc = canvas.getContext("2d");
var mgnt = canvas.getContext("2d");
//then angle anf power values goes into another function
<form id="info">
Power:<br>
<input type="number" name="power" id="power"><br>
Angle:<br>
<input type="number" name="angle" id="angle"/>
<input type="submit" value="Submit"/>
</form>
我的问题是我给出的任何输入警报给我0.如果我给角度输入与decleration(var angle = 30;)而不是html输入一切正常。有什么问题
谢谢你们,我修好了:)
答案 0 :(得分:2)
您需要动态 获取值更改或"submit"
事件
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
let form = document.getElementById("info");
form.addEventListener("submit", function (e) {
// Don't submit form! (Remove this line later - so you can submit! ;))
e.preventDefault();
var angle = Number(form.angle.value);
alert( angle )
});
&#13;
Enter an angle and hit SUBMIT
<form id="info">
Power:<br>
<input type="number" name="power" id="power"><br>
Angle:<br>
<input type="number" name="angle" id="angle" />
<input type="submit" value="Submit" />
</form>
&#13;
您的JS在从上到下立即(尽可能)执行的方式中是同步的。那时没有分配者也没有输入价值。相反,在submit
,你可以去元素值!或者<input>
"input"
事件:
const angle = document.getElementById("angle");
angle.addEventListener("input", function () {
const val = Number( this.value );
console.log( val );
// do someting smart with #angle's val
});
&#13;
Enter an angle and watch it happen ;)
<form id="info">
Power:<br>
<input type="number" name="power" id="power"><br>
Angle:<br>
<input type="number" name="angle" id="angle" />
<input type="submit" value="Submit" />
</form>
&#13;
在这里输入代码
答案 1 :(得分:1)
现在您正在尝试立即获取表单值。
在表单提交后获取表单值。
form.onSubmit = function() {
var angle = Number(form.angle.value);
// rest of the logic
}