【发布时间】:2026-02-03 14:00:02
【问题描述】:
在 JS 我有
$("#index").on({
click : function() { // do something useful with $(this)....}
},"li.superclass");
我如何用 CoffeeScript 来描述这一点?
【问题讨论】:
标签: jquery coffeescript
在 JS 我有
$("#index").on({
click : function() { // do something useful with $(this)....}
},"li.superclass");
我如何用 CoffeeScript 来描述这一点?
【问题讨论】:
标签: jquery coffeescript
几乎一样:
$("#index").on click: ->
alert ("hi")
, "li.superclass"
【讨论】:
.on会尝试对选择器本身的字符串进行操作。
$index = $ "#index"; $index.on click: -> alert "hi", "li.superclass"
这就是你想要的:
$("#index").on
click:->
alert "hi"
"li.superclass"
但我认为这更清楚:
events =
"click":->
alert "hi"
$("#index").on events, "li.superclass"
【讨论】:
如果您需要在处理程序中使用 this/@,我认为您正在寻找类似 CoffeeScript 的胖箭头,它会为您重新绑定 this...
$('#index').on 'click', => alert(@)
请注意,您需要使用off 来删除处理程序,否则它可能不会被垃圾回收。 Backbone 0.9 引入了a listenTo function,这使得管理事件处理程序更加理智。
【讨论】: