这是我的观点:
<a href="#" onclick="delete_quote(this);" class="quote-delete">
<i class="fi-x small-1"></i>
</a>
这是我的 CoffeeScript 文件:
$(document).ready ->
$('a.quote-delete').hide()
$('div.quote').mouseenter ->
$(this).children('a.quote-delete').show()
$('div.quote').mouseleave ->
$(this).children('a.quote-delete').hide()
delete_quote = (element) ->
alert 'hi'
$(document).ready 部分工作正常,但是当我按下链接时,我没有收到“two”消息,并且浏览器控制台中出现错误:
Uncaught ReferenceError: delete_quote is not defined
这是编译后的JS文件:
(function() {
var delete_quote;
$(document).ready(function() {
$('a.quote-delete').hide();
$('div.quote').mouseenter(function() {
return $(this).children('a.quote-delete').show();
});
return $('div.quote').mouseleave(function() {
return $(this).children('a.quote-delete').hide();
});
});
delete_quote = function(element) {
return alert('hi');
};
}).call(this);
最佳答案
CoffeeScript 将 delete_quote
函数放入函数闭包中,因此不是页面上全局上下文的一部分。 onclick
处理程序中的函数正在全局上下文中调用。
在这方面,CoffeeScript 需要一些额外的帮助。我对 JavaScript 非常熟悉,是 CoffeeScript 的初学者,因此下面的代码可能不起作用,但应该可以为您提供基本的想法。您必须将该函数定义为 window
对象的一部分:
window.delete_quote = (element) ->
alert 'Hi'
编辑:您也可以尝试:
this.delete_quote = (element) ->
alert 'Hi'
另一个 StackOverflow 问题也可能有帮助:CoffeeScript: coffee -w name-of-file.coffee complains: “window is not defined” -- 虽然这个问题更多地与在 Node 和浏览器中运行 CoffeeScript 编译的 JavaScript 有关,但它涉及如何定义“全局”变量和函数。
关于javascript - 从 Rails View 调用 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24803164/