【问题标题】:How to check syntax error in coffeescript如何检查coffeescript中的语法错误
【发布时间】:2021-09-29 23:12:05
【问题描述】:

我不熟悉咖啡脚本,我尝试将 jquery 从视图中移到资产中,但无法使其工作。

这里是工作视图:

- jquery_ready do
  $('label[for=voucher_name], input#voucher_name').hide();
  $( "#voucher_voucher_provider_id" ).change(function() {
  var exist_id = $(this).val();
  var ids = $('#voucher_false_ids_')[0].value;
  if(jQuery.inArray(exist_id, ids.split(" ")) !== -1){
  $('label[for=voucher_name], input#voucher_name').hide();
  }
  else
  {
  $('label[for=voucher_name], input#voucher_name').show();
  }
  });
                                                                                                              

然后在 /app/assets/javascript/mycode.js.coffee 中

jQuery ->
  $('label[for=voucher_name], input#voucher_name').hide();
  $( "#voucher_voucher_provider_id" ).change ->
    exist_id = $(this).val();
    ids = $('#voucher_false_ids_')[0].value;
    alert('alert');
    If(jQuery.inArray(exist_id, ids.split(" ")) !== -1)
      $('label[for=voucher_name], input#voucher_name').hide();
    else
      $('label[for=voucher_name], input#voucher_name').show();

到目前为止,我可以一直运行到 .change -> 警报(“警报”); 不是在我开始把所有行放在 If 之后

导致错误的原因:

ExecJS::RuntimeError at /admin
SyntaxError: [stdin]:6:51: unexpected =

帮助:正确的语法或来自 /Thanks 的错误是什么

【问题讨论】:

  • 跳出两件事:If 应该是 if!== 应该是 !=。或者只是将 JavaScript 保留为 JavaScript。
  • 它成功了,请你把你的评论移到回答我接受/谢谢
  • 请随意使用 Alex 的回答,他的回答比我的快速评论更详细。

标签: javascript jquery ruby-on-rails coffeescript


【解决方案1】:

如果您将该 sn-p 粘贴到 CoffeeScript 网站的 the "Try CoffeScript" page,它会告诉您出了什么问题。

上面写着:

[stdin]:7:51: error: unexpected =
    If(jQuery.inArray(exist_id, ids.split(" ")) !== -1)
                                                  ^

CoffeeScript 没有 ===!== 运算符。 ==!= 在为您编译时被翻译为它们的严格等价物。

如果你修复它,你会得到另一个错误:

[stdin]:8:1: error: unexpected indentation
      $('label[for=voucher_name], input#voucher_name').hide();
^^^^^^

这是因为上一行。您以If 开始一个if 语句,因此CoffeeScript 不会将此视为if 语句,而是将其视为对If() 函数的函数调用。

将其更改为小写if,然后编译就好了。


短版,这里是固定的:

jQuery ->
  $('label[for=voucher_name], input#voucher_name').hide();
  $( "#voucher_voucher_provider_id" ).change ->
    exist_id = $(this).val();
    ids = $('#voucher_false_ids_')[0].value;
    alert('alert');
    if(jQuery.inArray(exist_id, ids.split(" ")) != -1)
      $('label[for=voucher_name], input#voucher_name').hide();
    else
      $('label[for=voucher_name], input#voucher_name').show();

【讨论】:

  • If(jQuery.inArray(exist_id, ids.split(" ")) !== -1) 实际上在 coffescript 和 JS 中都被视为函数调用。是的,JS 实际上会让你定义一个名为 If 的函数。
猜你喜欢
  • 1970-01-01
  • 2014-08-28
  • 2012-08-11
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多