通过传递参数来更新`[] .forEach.call()`中的值

时间:2019-11-11 16:02:15

标签: javascript

如何摆脱有线的NULL 部分或传递参数以更新计数器?

该代码在内部具有一个函数,该函数将新值设置为名为[].forEach.call(counters, function(counter) {...的计数器。我想不通一种方法来访问[].forEach.call(...并传递新参数...

我想通过传递类似这样的参数来使用普通函数来更新值:

setValue(currentValue);

这是原始代码(当然,您只需要修改JS!),在此代码中,我使用setTimeout来更新计数器:

setValue()
function update(newValue){
// everything goes here
};
let counters = document.getElementsByClassName('number-ticker');

let defaultDigitNode = document.createElement('div');
defaultDigitNode.classList.add('digit');

for (let i = 0; i < 11; i++) {
  defaultDigitNode.innerHTML += i + '<br>';
}




[].forEach.call(counters, function(counter) {
  
  let d = defaultDigitNode.cloneNode(true);
  let digit = counter.appendChild(d);
  let currentValue = 10; //set initiale value
  setValue(currentValue);
  
  //update the value
  setTimeout(function(){
  setValue(9);
  }, 1000)

  function setValue(number) {
    digit.style.marginTop = '-' + number + 'em';
  }
});

我们只能在代码中的:root { background-color: #555; color: white; font-size: 25vh; font-family: Roboto Light; } body, html { margin: 0; height: 100%; } .container { display: flex; justify-content: center; align-items: center; height: 100%; } .number-ticker { overflow: hidden; height: 1em; background-color: #333; box-shadow: 0 0 0.05em black inset; } .number-ticker .digit { float: left; line-height: 1; transition: margin-top 1.75s ease; border-right: 1px solid #555; padding: 0 0.075em; text-align: center; }内更新参数并将其传递给<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Number Ticker</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="number-ticker.css"> </head> <body> <div class="container"> <div class="number-ticker" data-value="10"></div> </div> <script src="number-ticker.js"></script> </body> </html>。如果我们想在setValue之外更新[].forEach.call()

怎么办?

1 个答案:

答案 0 :(得分:1)

我认为您过度设计了解决方案,这是我的建议:

我正在使用Array.from和Array.keys生成一个数组,并对其进行airflow variables -i /path/to/var.json 循环。在我的for循环中,我正在运行for更新我的计数器。

setTimeout
function setValue(number) {
  let digit = document.getElementsByClassName('digit')[0];
  digit.innerHTML = number;
}

const currentValue = 10;

Array.from(Array(currentValue).keys()).reverse().forEach(function(number,index) {
    setTimeout(function(){
        setValue(number + 1, index);
    }, index * 1000);
});
:root {
  background-color: #555;
  color: white;
  font-size: 25vh;
  font-family: Roboto Light;
}

body,
html {
  margin: 0;
  height: 100%;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.number-ticker {
  overflow: hidden;
  height: 1em;
  background-color: #333;
  box-shadow: 0 0 0.05em black inset;
}

.number-ticker .digit {
  float: left;
  line-height: 1;
  transition: margin-top 1.75s ease;
  border-right: 1px solid #555;
  padding: 0 0.075em;
  text-align: center;
}

希望这会有所帮助!