Javascript &引用;。。。不是一个函数;错误
我正在尝试用咖啡脚本制作一个非常基本的东西:Javascript &引用;。。。不是一个函数;错误,javascript,jquery,coffeescript,Javascript,Jquery,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[op
...
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(+']'));
});
$('.addOption')。在('click',function()上{
var内容,新选项,nextId;
nextId=$('.optionsTemplate').prev().children().length+1;
contents=“”+$(“.optionsTemplate”).html()+”;
$(此)。之前(内容);
newOption=$('.optionsTemplate').prev().children().eq(-1).find('.text_字段');
newOption.attr('id','item_options_uu'+nextId);
返回newOption.attr('name','item[options]['+nextId(+']');
});
我觉得还可以
return newOption.attr('name', 'item[options][' + nextId(+']'));
改为
return newOption.attr('name', 'item[options][' + nextId +']');
如前所述,问题存在于最后一行:
newOption.attr 'name', 'item[options]['+ nextId +']'
问题是CoffeeScript将nextId视为一个函数。原因是+符号和']'字符串之间没有空格
按如下方式添加空格:
newOption.attr 'name', 'item[options]['+ nextId + ']'
使一切按预期进行。使用CoffeeScript时需要注意的一点是,由于存在大量空白,第一次使用CoffeeScript时可能会出现问题。请添加编译后的输出,只是在没有返回语句的情况下尝试了一下。这无助于编译后的输出中倒数第二行:
nextId(
语法错误