javascript - 添加输入参数时moveBall函数不起作用
问题描述
我正在尝试创建一个 moveBall 函数,如果您将在 HTML 中创建的球的 ID 放入,它会从左向右移动。
这是我首先做的,它有效:
var ball = document.getElementById("ball");
var velocityX = 100;
var positionX = 0;
var reverseX = false;
//write a function that can change the position of the html element "ball"
function moveBall() {
// two fixed x-axis coordinates (you will use these variable in step 3)
var Xmin = 0;
var Xmax = 500;
//reverse condition
if (!reverseX){
positionX = positionX + velocityX;
} else positionX = positionX - velocityX;
ball.style.left = positionX + 'px';
if (positionX === Xmax){
reverseX = true;
} else if (positionX === Xmin){
reverseX = false;
}
}
// This call the moveBall function every 100ms
setInterval(moveBall, 100);
但是,当我尝试创建一个函数 moveBall(ballId) 以便我可以将它与其他球一起使用时,它不起作用。这是我的代码:
var ballId;
var velocityX = 100;
var positionX = 0;
var reverseX = false;
//write a function that can change the position of the html element "ball"
function moveBall(ballId) {
ball = document.getElementById(ballId)
// two fixed x-axis coordinates (you will use these variable in step 3)
var Xmin = 0;
var Xmax = 500;
//reverse condition
if (!reverseX){
positionX = positionX + velocityX;
} else positionX = positionX - velocityX;
ball.style.left = positionX + 'px';
if (positionX === Xmax){
reverseX = true;
} else if (positionX === Xmin){
reverseX = false;
}
}
// This call the moveBall function every 100ms
setInterval(moveBall("ball"), 100);
如果你有任何线索,我会很高兴知道。球不会随着第二个代码移动,它只是在 html 文件中保持静态。
解决方案
你的问题就在上面写着的那一行setInterval(moveBall("ball"), 100);
setInterval
期望一个函数作为第一个参数,但是,这里提供的是一个函数调用。我在这里的理论有点生疏,但基本上这将首先执行函数调用,它会返回undefined
,然后你的行看起来就像你写的一样setInterval(undefined, 100);
,所以每 100 毫秒你什么都不做......
你想要做的是编写函数处理程序来传递setInterval
而不是函数调用。
您可以使用箭头功能setInterval(() => moveBall("ball"), 100);
,或者如果您不能使用箭头功能,您可以使用setInterval(function () {moveBall("ball")}, 100);
换句话说,这表示每 100 毫秒执行一次(无名)函数,这个无名函数将moveBall
使用所需的参数执行您的函数的调用。
您没有参数的原始代码可以工作,因为如果您仔细观察,您会直接在那里传递函数,而无需调用。
推荐阅读
- html - 如何在 Jinja 模板中设置一个值并将其传递给 javascript 变量
- javascript - 如何在玩笑中隐藏 React-Error-Boundary 控制台错误
- vba - 如何知道是否收到或发送了电子邮件?
- r - R:使用 lapply -> args 的 MaxEnt 物种分布建模暗示不同的行数
- python - 修复在 python 中从右到左书写
- python - 在 openCV 或其他工具中将字节转换为 mp4 视频作为 numpy
- reactjs - 如何使用两个用useEffect更新相同状态的函数?
- c# - Unity GameObject.SetActive 不起作用
- reactjs - antd 选择清除值
- alias - 如何为 bash .profile 中的路径创建别名?