How do I call a JavaScript function from an html.erb

前端 未结 1 1199
清歌不尽
清歌不尽 2021-01-19 00:18

How do I call a JavaScript function from html.erb

in application.js

function displayClock() {
  var digital = new Date();
  var hour         


        
相关标签:
1条回答
  • 2021-01-19 00:54

    You probably need to use proper tag to indicate that you're writing JS code:

    <script type="text/javascript">
      displayClock();
    </script>
    

    Plus, since you probably use jQuery (it's default in Rails), you may want to make sure the function is called after whole document is loaded:

    <script type="text/javascript">
      $(document).load(function(){
        displayClock();
      });
    </script>
    

    I'd also advice you not to write your JS in application.js and use this file only as a manifest file, which includes your other scripts through Rails asset pipeline.

    Also you can take advantage of the javascript helper javascript_tag in your html.erb file

    <%= javascript_tag "displayClock()" %>
    
    0 讨论(0)
提交回复
热议问题