将变量设置为2,但console.log表示它未定义

时间:2018-01-19 14:46:55

标签: javascript jquery html

为了简要概述我正在创建一个加载栏,根据拖放到地图上的引脚总数,需要从0到100,而不是有多少个可能的位置。所以,我对于如何实现这一目标有一些逻辑。

//pin drop counter
var pDrop = 2;
//secondary drop counter
var dropCounter = pDrop
//result length counter
var rLength;

//pin drops and then runs the check marker count function
function dropPin(){ checkMarkerCount() }

//if a new pin was dropped then we increase the size of the bar 
function checkMarkerCount() {
  if (dropCounter != pDrop) {
    moveBar();
  }

 function moveBar() {
   //selects the loading bar from the DOM
   var barEl = document.getElementById("pro-bar");   
   //states how wide the bar is
   var barW = 1; 
   //dictates how fast it moves
   var barid = setInterval(frame, 10);
   //gets how many pins have dropped
   var counter = pDrop; 

  function frame(counter) {
    //rLength is the length of an array = the total amount of possible pin drops
    if (counter >= rLength) {
      clearInterval(barid);
    } else {
      barW = counter; 
      barEl.style.width = barW + '%'; 
      console.log(barW)
    }
  }
}
}

问题在于,即使我说pDrop等于2,它也会记录长度未定义....我做错了什么?

1 个答案:

答案 0 :(得分:1)

你必须理解变量和参数的概念。

function frame(i_counter) {
    //rLength is the length of an array = the total amount of possible pin drops
    if (i_counter >= rLength) {
      clearInterval(barid);
    } else {
      barW = i_counter; 
      barEl.style.width = barW + '%'; 
      console.log(barW)
    }
  }

当您致电function frame时,您应设置参数i_counter。 您认为您作为参数传递的counter与您在上面设置的相同。 代码上的barW = counter采用您设置的参数。

我稍微更改了你的代码,所以你没有摆脱counter参数。 执行框架时,请执行以下操作:

setInterval(function () {
   frame(2);
}, 10);