javascript - 从 Rails View 调用 JS 函数

标签 javascript ruby-on-rails coffeescript

这是我的观点:

<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/

相关文章:

javascript - moment.js 无法将 utc 日期转换为本地日期

javascript - 如何在 React 中将状态从钩子(Hook)传递到 App 钩子(Hook)中显示?

ruby-on-rails - Rails 全局变量 : is global variable share between http requests?

ruby-on-rails - 给定一个字符串,判断它是否来自 .html_safe 调用?

javascript - AngularJS + Rails : Unknown provider: e

javascript - 什么是 "Escaped"& "Unescaped"输出

javascript - Coffeescript:如何一行导入express模块

javascript - 如何通过点击将变量(数字ID)从一个页面传递到另一个页面

ruby-on-rails - 如何从 Ruby 1.9.2 降级到 Ruby 1.8.7 以运行 Rails 2.0.2

javascript - 将 PHP 变量分配给 JavaScript 变量,值正在消失