CoffeeScript和上下文

时间:2018-06-06 18:11:47

标签: javascript coffeescript

我尝试使用触发事件的上下文获取值$(this),但我收到以下错误:

  

未捕获的TypeError:无法读取属性' toLowerCase'未定义的

cants_field_hidden = document.createElement('input')
cants_field_hidden.setAttribute 'type', 'hidden'
cants_field_hidden.setAttribute 'id', 'cant_' + if id == undefined then item_id else id
cants_field_hidden.classList.add 'cant_input'
cants_field_div.append cants_field_hidden

cants_field_visible = document.createElement('input')
cants_field_visible.setAttribute 'type', 'number'
cants_field_visible.setAttribute 'placeholder', 'Porciones'
cants_field_visible.setAttribute 'name', 'ammounts[]'
cants_field_visible.setAttribute "onkeypress", calculate_carbohydrates((if id == undefined then item_id else id), (if 
carbohydrates == undefined then item_carbohydrates else carbohydrates))
cants_field_visible.setAttribute 'required', true
cants_field_div.append cants_field_visible

function calculate_carbohydrates(id, carbohydrates){
  console.log($(this))
  console.log(id)
  console.log(carbohydrates)

  var input = document.getElementById('cant_' + id)
  var total_carbohydrates = $(this).val() * carbohydrates

  input.value = parseInt(total_carbohydrates)

  var sum = 0;
  $(".cant_input").each(function(){
    sum += Number($(this).val())
  })
  $("#total_carbohydrates").val(sum).trigger('change')
  $("#total_carbohydrates_span").text($("#total_carbohydrates").val())
}

1 个答案:

答案 0 :(得分:0)

寻找解决方案

{{1}}