【问题标题】:How to call JavaScript functions from Rails views?如何从 Rails 视图调用 JavaScript 函数?
【发布时间】:2015-04-20 09:44:36
【问题描述】:

我有弹出新屏幕的 JavaScript 函数,我需要在 Rails 视图中使用它们。

这是/app/assets/signup.js中的脚本:

<script type="text/javascript">

  function popup() {
    cuteLittleWindow = window.open("signup.html", "littleWindow", "location=no,width=320,height=200");
  }

</script>

如何在我的/views/index.html.erb 中使用 JavaScript 函数?

【问题讨论】:

  • 只需将包含&lt;script&gt; 标签的相同代码放入您的index.html.erb 文件中

标签: javascript html ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

将以下代码放在结束正文标记之前,如下所示:

<body>
  <!-- Your body things -->

  <script>

  $(function(){

    function popup(){ 
      cuteLittleWindow = window.open("signup.html", "littleWindow", "location=no,width=320,height=200"); 
    }

  });

  </script>

</body>

【讨论】:

  • 这样,该功能将在每个页面上都可用,即使它打算仅在特定页面上使用。
【解决方案2】:

在 index.html.erb 中

#####your view code

<script type="text/javascript">
$(document).ready(function(){

  function popup(){ 
    cuteLittleWindow = window.open("signup.html", "littleWindow", "location=no,width=320,height=200"); 
  }

})//document ends
</script>

使用 Rails turbolinks 你必须监听 turbolinks:load 事件:

$(document).on "turbolinks:load", ->
  alert "page has loaded!"

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多