如何从erb模板调用JavaScript函数? [英] How do I call a JavaScript function from an erb template?

查看:94
本文介绍了如何从erb模板调用JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您定义JavaScript函数然后从erb模板调用它,则不会调用该函数。为什么?单击此链接应显示警告,但不会显示。

If you define a JavaScript function and then call it from an erb template the function does not get called. Why? Clicking this link should show an alert, but it does not.

= link_to "Add Sprout", new_sprout_path, remote: true

控制器:

def new
  @sprout = Sprout.new
  respond_to { |format| format.js }
end

然后在模板中我调用一个函数:

Then in the template I call a function:

# sprouts/new.js.erb
doSomething();

该函数在我的js文件中定义:

The function is defined in my js files:

# javascripts/sprouts.js.coffee
doSomething = ->
  alert "yum ghum I am a new sprout."

JavaScript回来了。我可以在控制台中看到它。但我看不到警报。为什么这不起作用?

The JavaScript comes back. I can see it in the console. But I see no alert. Why doesn't this not work?

我正在使用Rails 4。

I'm using Rails 4.

推荐答案

@doSomething = -> alert "yum ghum I am a new sprout."

window.doSomething = -> alert "yum ghum I am a new sprout." # I prefer this approach, as it's more explicit.

这篇关于如何从erb模板调用JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆