当我从绘制循环中获取它定义的 HTML 值时,但如果我在它进入循环之前加载它,它似乎会忘记它。
这是我将范围缩小到的代码:
<html>
<head>
<script type="application/javascript">
setInterval(draw,120);
var value = document.getElementById("uniqueID").value
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.strokeText(value, 200, 200);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="500" height="500"></canvas>
<input type="text" name="name" id="uniqueID" value="5" /><br>
</body>
</html>
像这样的代码不起作用。文本说该值未定义。 但是如果我将“var value = do...”移动到绘制函数之后,它就会得到它。
我需要在绘制函数之外定义值。我怎样才能做到这一点?
谢谢
最佳答案
But if i move the "var value = do..." to after the draw function it gets it.
我认为你错了,因为具有 id uniqueID 的元素在绘图函数之外的任何地方都不存在。这是因为您的脚本 block 是在具有 uniqueID 的元素之前执行的。
您可以在创建元素后添加整个脚本 block 并添加文档类型定义:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<input type="text" name="name" id="uniqueID" value="5" /><br>
<script type="application/javascript">
setInterval(draw,120);
var value = document.getElementById("uniqueID").value
function draw() {
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.strokeText(value, 200, 200);
}
}
</script>
</body>
</html>
关于javascript - 当 JS 进入绘制循环时,如何使从 HTML 表单加载的 JS 中的值保持定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769003/