CoffeeScript 混乱? (KeyUp Jquery)
我刚刚开始使用 CoffeeScript 来看看有什么大惊小怪的,我喜欢它。然而,在将我的旧脚本转换为咖啡时遇到了一个问题:
$(function() {
$(create_MP).keyup(function(e){
if(e.which == 16) {
isShift = false;
}
});
});
这是我之前的 JQuery,所以我尝试将其转换为咖啡脚本:
jQuery ->
$(create_MP).keyup(e) ->
if e.which == 16
isShift = false
但是在打开控制台时出现此错误:
application.js :23Uncaught TypeError: 对象 [object Object] 没有方法 'keyUp'
有
什么想法吗?
I've just started using coffeescript to see what all the fuss is about and I love it. However there is a problem I had when converting an old script of mine over to coffee:
$(function() {
$(create_MP).keyup(function(e){
if(e.which == 16) {
isShift = false;
}
});
});
That's the JQuery that I had before so I tried to transform it into coffeescript:
jQuery ->
$(create_MP).keyup(e) ->
if e.which == 16
isShift = false
But I get this error when opening the console:
application.js:23Uncaught TypeError: Object [object Object] has no method 'keyUp'
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论如何,该代码都是错误的。您发布的 CoffeeScript 与此等效:
也就是说,您正在调用
keyup(e)
的结果并向其传递一个函数。您想要的是使用该函数作为参数来调用keyup()
。解决这个问题的最简单方法就是在keyup
和(e) ->
之间添加一个空格。That code is wrong regardless. The CoffeeScript you posted is equivalent to this:
That is, you're calling the result of
keyup(e)
and passing a function to it. What you want is to callkeyup()
with the function as an argument. The simplest way to fix it would just to put a space betweenkeyup
and(e) ->
.您在评论中指出的问题并不是您唯一的问题。您需要在
(e)
之前添加一个空格,否则 CoffeeScript 会认为您正在尝试使用参数e
调用keyup
函数。您想说的是:如果没有空格,您的 JavaScript 将如下所示:
这没有任何意义,因为
keyup(e)
不会返回函数。但是,如果添加空格,那么(e) ->
就会成为接受单个e
参数的匿名函数的定义:这不仅有意义,它也会做你想要它做的事情。
The problem you note in your comment isn't your only problem. You need to a space before
(e)
or CoffeeScript will think you're trying to call thekeyup
function with an argument ofe
. You want to say this:Without the space, your JavaScript will look like this:
and that doesn't make any sense since
keyup(e)
won't return a function. But, if you add the space, then(e) ->
becomes a definition of an anonymous function which takes a singlee
argument:and not only does that make sense, it does what you want it to do as well.