简体   繁体   English

JavaScript到CoffeeScript错误

[英]JavaScript to CoffeeScript Error

I have a function that toggles all of the others checkboxes when the last checkbox is clicked. 我有一个功能,当单击最后一个复选框时,可以切换所有其他复选框。

It works perfectly in ordinary JavaScript: 它可以在普通JavaScript中完美运行:

$(document).ready(function() {
  $('#manage').click(function(event) {   
      if(this.checked) {
          $('.checkbox:checkbox').each(function() {
              this.checked = true;                        
          });
      }
      if(!this.checked) {
          $('.checkbox:checkbox').each(function() {
              this.checked = false;                        
          });
      }
  });
});

http://jsfiddle.net/PauaN/9/ http://jsfiddle.net/PauaN/9/

However when I compile into CoffeeScript (using http://js2coffee.org/ ) the functionality breaks when the checkboxes are toggled off: 但是,当我编译为CoffeeScript(使用http://js2coffee.org/ )时,如果取消选中复选框,则功能会中断:

$(document).ready ->
  $("#manage").click (event) ->
    if @checked
      $(".checkbox:checkbox").each ->
        @checked = true

    unless @checked
      $(".checkbox:checkbox").each ->
        @checked = false

http://jsfiddle.net/FRs5d/7/ http://jsfiddle.net/FRs5d/7/

I think this is because the second each loop is only running once. 我认为这是因为第二个每个循环仅运行一次。

What's going wrong? 怎么了

The problem is the following. 问题如下。 In the converted script the implicit return created by CoffeeScript is false 在转换后的脚本中,CoffeeScript创建的隐式返回为false

unless @checked
  $(".checkbox:checkbox").each () ->
    @checked = false
    # here false is returned stopping the each function from continuing

so the solution is adding true at the end of the function 所以解决方案是在函数末尾添加true

unless @checked
  $(".checkbox:checkbox").each () ->
    @checked = false
    true

This fiddle shows it in action. 这个小提琴显示了它的作用。

Two things happens: 发生两件事:

  1. Coffee Script puts return at end of every function, so @checked = true changes into return this.checked = true; Coffee Script将return放在每个函数的末尾,因此@checked = true更改为return this.checked = true;
  2. If function in Jquery each() returns false , it does not continue. 如果Jquery中的function each()返回false ,则该函数不会继续。

What will solve this, is changing your last line 解决此问题的方法是更改​​您的最后一行

@checked = false

to something like this: 像这样:

@checked = false
return true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM