如何将jQuery的keyup上的输入值推入数组

时间:2017-06-20 18:09:25

标签: javascript arrays

基本上我有一堆使用Rails Cocoon库的嵌套表单,并且有多个.stage-time.stop_time输入(取决于表单的数量)。

基本上,我的计划是......

  • .stage-time.stop_time密钥上,获取this输入值
  • 根据您所使用的形式...将其推送到数组
  • 将其推送到数组
  • 最后用阵列做点什么......

var stopTimeArray = []

$('.mdl-textfield__input.stage-time.stop_time').keyup('input', function() {

  var stopTimeVal = parseInt(this.value)
  // index gets the rel of the current form. This works perfectly!
  var index = parse($(getCurrentStage()).attr('rel')) - 1 
  // if you are on the first form, push the stopTimeVal in the 0th index of array
  stopTimeArray[index] = stopTimeVal
  updateTTH()
}

function updateTTH() {
  console.log(stopTimeArray)
  // other code...
}

但是当我以第二种形式输入内容时会出现问题。它将undefined分配给之前的所有元素。

假设我在第一个表单中输入 20 updateTTH()将打印

  

=> [20]

     

=> [20]   (两次因为它两次触发keyup)

但......以第二格式...假设我输入 30 ... updateTTH()将打印

  

=> [undefined×1,30]

     

=> [undefined×1,30]

我猜这种情况正在发生,因为.keyup()方法上不再存在stopTimeArray [index - 1] ...但是,我尝试了很多事情,但我没有想法。

HERE is a YouTube video of the problem

0 个答案:

没有答案