首页 > 解决方案 > 添加输入参数时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 文件中保持静态。

标签: javascripthtmlparameters

解决方案


你的问题就在上面写着的那一行setInterval(moveBall("ball"), 100);

setInterval期望一个函数作为第一个参数,但是,这里提供的是一个函数调用。我在这里的理论有点生疏,但基本上这将首先执行函数调用,它会返回undefined,然后你的行看起来就像你写的一样setInterval(undefined, 100);,所以每 100 毫秒你什么都不做......

你想要做的是编写函数处理程序来传递setInterval而不是函数调用。

您可以使用箭头功能setInterval(() => moveBall("ball"), 100); ,或者如果您不能使用箭头功能,您可以使用setInterval(function () {moveBall("ball")}, 100);

换句话说,这表示每 100 毫秒执行一次(无名)函数,这个无名函数将moveBall使用所需的参数执行您的函数的调用。

您没有参数的原始代码可以工作,因为如果您仔细观察,您会直接在那里传递函数,而无需调用。


推荐阅读