[英]Call JS function from Rails view
Here is my view: 这是我的看法:
<a href="#" onclick="delete_quote(this);" class="quote-delete">
<i class="fi-x small-1"></i>
</a>
Here is my coffee script file: 这是我的咖啡脚本文件:
$(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'
The $(document).ready part works fine, but when i press the link I don't get the 'two' message and I have the error in browser console: $(document).ready部分工作正常,但是当我按链接时,我没有收到“ two”消息,并且在浏览器控制台中出现错误:
Uncaught ReferenceError: delete_quote is not defined
Here is compiled JS file: 这是编译的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 is putting the delete_quote
function inside a function closure, and is therefore not part of the global context on the page. CoffeeScript会将
delete_quote
函数放入函数闭包内,因此不属于页面上全局上下文的一部分。 The function in the onclick
handler is being invoked in the global context. 在全局上下文中调用
onclick
处理程序中的函数。
In this regard, CoffeeScript needs a little extra help. 在这方面,CoffeeScript需要一点额外的帮助。 I'm very familiar with JavaScript, a beginner at CoffeeScript, so the following code might not work but should give you the basic idea.
我对CoffeeScript的初学者JavaScript非常熟悉,因此以下代码可能不起作用,但应该可以带给您基本的思想。 You'll have to define the function as part of the
window
object: 您必须将函数定义为
window
对象的一部分:
window.delete_quote = (element) ->
alert 'Hi'
Edit: You might also try: 编辑:您也可以尝试:
this.delete_quote = (element) ->
alert 'Hi'
This other StackOverflow question might be helpful as well: CoffeeScript: coffee -w name-of-file.coffee complains: “window is not defined” -- though the question has more to do with running CoffeeScript compiled JavaScript in Node and the browser, but it touches on how to define "global" variables and functions. 其他另一个StackOverflow问题也可能会有所帮助: CoffeeScript:coffee -w-file-name.coffee抱怨:“未定义窗口” -尽管该问题与在Node和浏览器中运行CoffeeScript编译的JavaScript有关,但它涉及如何定义“全局”变量和函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.