【问题标题】:"... is not a function" error“...不是函数”错误
【发布时间】:2013-01-04 06:14:17
【问题描述】:

我正在尝试在 CoffeeScript 中做一个非常基本的东西:

...
nextId = $('.optionsTemplate').prev().children().length + 1
# 'alert nextId' gives 4, which is correct
...
newOption = /*selector of new option*/
newOption.attr 'id', 'item_options_' + nextId
newOption.attr 'name', 'item[options]['+ nextId +']'

所以当我调用“nextId”时(设置 id 和名称时)- JS 控制台说“nextId 不是函数”

我尝试了几件事:

# get text instead of integer
nextId.text()

# make a function
getNextId = () ->
  $('.optionsTemplate').prev().children().length + 1

遇到同样的错误。


这是编译后的输出:

$('.addOption').on('click', function() {
  var contents, newOption, nextId;
  nextId = $('.optionsTemplate').prev().children().length + 1;
  contents = "<div class='row'>" + $('.optionsTemplate').html() + '</div>';
  $(this).before(contents);
  newOption = $('.optionsTemplate').prev().children().eq(-1).find('.text_field');
  newOption.attr('id', 'item_options_' + nextId);
  return newOption.attr('name', 'item[options][' + nextId(+']'));
});

我觉得还可以。

【问题讨论】:

  • 请添加编译输出
  • 刚刚尝试没有返回语句 - 没有帮助
  • 编译输出中倒数第二行:nextId( 语法错误

标签: javascript jquery coffeescript


【解决方案1】:
return newOption.attr('name', 'item[options][' + nextId(+']'));

上面改为

return newOption.attr('name', 'item[options][' + nextId +']');

【讨论】:

    【解决方案2】:

    如前所述,问题存在于最后一行:

    newOption.attr 'name', 'item[options]['+ nextId +']'
    

    问题在于 CoffeeScript 将 nextId 视为一个函数。原因是+号和']'字符串之间没有空格。

    添加空格如下:

    newOption.attr 'name', 'item[options]['+ nextId + ']'
    

    使一切按预期工作。这只是使用 CoffeeScript 需要注意的事情之一 - 由于大量空白,事情并不总是像您第一次预期的那样工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 2017-05-09
      • 2021-09-14
      • 2021-05-10
      • 2017-02-06
      • 2013-11-04
      • 2015-09-23
      相关资源
      最近更新 更多