Gid*_*eek 4 javascript coffeescript
我正在尝试编写一些CoffeScript函数,在检查表中的复选框时检查表中的所有复选框.
我在CoffeeScript中的功能如下所示:
$("table.tableview th input:checkbox").live 'click', ->
checkedStatus = this.checked
$("table.tableview tbody tr td:first-child input:checkbox").each ->
this.checked = checkedStatus
Run Code Online (Sandbox Code Playgroud)
它非常适合检查所有方框.但是,取消选中它不起作用.编译好的JS看起来像这样:
$("table.tableview th input:checkbox").live('click', function() {
var checkedStatus;
checkedStatus = this.checked;
return $("table.tableview tbody tr td:first-child input:checkbox").each(function() {
return this.checked = checkedStatus;
});
});
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为在第一个设置为false后,函数的返回将为false.但是我不知道如何抑制咖啡脚本的这种默认返回行为.请帮忙.
当我根据Flambino的建议添加"true"时,我得到以下JS
$("table.tableview th input:checkbox").live('click', function() {
var checkedStatus;
checkedStatus = this.checked;
$("table.tableview tbody tr td:first-child input:checkbox").each(function() {
return this.checked = checkedStatus;
});
return true;
});
Run Code Online (Sandbox Code Playgroud)
我可以在函数内部获取return语句的唯一方法是将它一直放在这样:
$("table.tableview tbody tr td:first-child input:checkbox").each ->
this.checked = checkedStatus
true
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?迄今为止的帮助
Tre*_*ham 19
如果您只是使用return(或等效地undefined)作为函数的最后一行,那么CoffeeScript编译器将为您提供JS return.因此,编写代码的最有效方法是
$("table.tableview th input:checkbox").live 'click', ->
checkedStatus = this.checked
$("table.tableview tbody tr td:first-child input:checkbox").each ->
this.checked = checkedStatus
return
return
Run Code Online (Sandbox Code Playgroud)
(当然,你可以安全地做到没有第二个return.只有返回值false在jQuery中有效.)
还有一个-/>用于定义没有返回值的函数的语法(); 见问题899.
只需添加一个true作为函数的最后一行,coffeescript将编译JS以返回:
$("table.tableview th input:checkbox").live 'click', ->
checkedStatus = this.checked
$("table.tableview tbody tr td:first-child input:checkbox").each ->
this.checked = checkedStatus
true
Run Code Online (Sandbox Code Playgroud)
换句话说,CoffeeScript总是返回最后一行的结果(就像Ruby一样)
编辑(问题更新后):
同样,你不能让CoffeeScript不返回函数中最后一行的值 - CoffeeScript的一部分就是它确实如此.
CoffeeScript具有重要的空白,因此缩进就是说什么属于一起 - 你的例子实际上是正确的:
$("table.tableview th input:checkbox").live 'click', ->
checkedStatus = this.checked
$("table.tableview tbody tr td:first-child input:checkbox").each ->
this.checked = checkedStatus
true // cause this function (the each-iterator) to return true
true // causes the click handler function to return true
Run Code Online (Sandbox Code Playgroud)
这与return true在javascript中编写函数之间没有区别.您只需使用空格而不是{}制作代码块.
| 归档时间: |
|
| 查看次数: |
7251 次 |
| 最近记录: |