简体   繁体   中英

Ruby on rails Call javascript Function

Here is my application.html.erb with the tag h1 and onclick execute JS function greatTutorial() .

## application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Dealabs</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="container">
      <%= render "layouts/navbar" %>
      <h1 onclick="greatTutorial()">Hello World</h1>
        <% if notice %>
          <p class="notice alert alert-info"><%= notice %></p>
        <% end %>
        <% if alert %>
          <p class="alert alert-danger"><%= alert %></p>

        <% end %>
      <%= yield %>
    </div>
  </body>
</html>

And my javascript/pack/application.js

##javascript/pack/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

function greatTutorial() {
    alert('Rails Guides are the best');
}

I followed multiple ask on that, but nothing work. If I replace my function onclick by h1 onclick="alert('danger')" is working fine. But I don't understand why my function greatTutorial is undefined (never exist).

Thanks !

There is a workaround, though. In Rails 6 you can change the function signatures from:

function myFunction() { ... }

to:

window.myFunction = function() { ... }

So according to your code try this :-

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


window.greatTutorial = function() {
    alert('Rails Guides are the best');
}

Rename your application.js to javascript.js or main.js

This is required if you have application.css and application.js inside packs directory. As webpack deals with css files in special way and create .js extensions.

Check out similar issue reported here for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM