0

我只是想让 Jquery 与我的 rails 应用程序一起工作。

我想在我的 new.html.erb 文件中放置一些 JQuery,我在 chrome 的控制台中收到以下错误:

 Uncaught SyntaxError: Unexpected token ( 

这是我的 new.html.erb:

<% provide(:title, "New Stat") %>
<% provide(:heading, "Welcome, #{ current_user.email }!") %>

<div id="stats-page-container">
  <div id="stat-form" >
    <div id="stat-form-inner"> 

    <% render 'layouts/init_stats_form' %> 
    <% render 'layouts/stat_input_form' %>

    <script>
       $.('#stat-form-inner').addClass('test-class');
    </script>

   </div>
 </div>
  <%= render 'layouts/progress' %> 
</div>

错误与 JQuery 代码一致:

$.('#stat-form-inner').addClass('test-class');

这是我的 application.html.erb 文件:

<html>
<head>
  <title><%= full_title(yield(:title)) %></title>    
  <h1> <%= yield(:heading) %> </h1>  
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= csrf_meta_tags %>
</head>
<body>
  <% flash.each do |key, value| %>
    <%= content_tag(:div, value, class: "alert alert-#{key}")%>
  <% end %>

  <%= render 'layouts/header' %>

  <% if user_signed_in? %>
    <%= render 'layouts/subheader' %>
  <% end %>

  <%= yield %>
  <%= debug(params) if Rails.env.development? %>

  <%= javascript_include_tag 'application' %>  
</body>
</html>  

并且具有该 id stat-form-inner 的元素没有添加该类。

我的 application.js 文件中有这个:

// = require jquery
// = require jquery_ujs
// = require_tree .  

我也加了

<%= javascript_include_tag 'application' %>   

直接在结束正文标签上方。

我还缺少什么?

谢谢!

4

3 回答 3

2
  1. 确保正确加载 JQuery。为此,删除/注释 $('#stat-form-inner').addClass('test-class') 并在 FF/chrome 中打开应用程序,然后在 Firebug 控制台中键入 $ 或 jQuery。如果它打印 function(),则 jQuery 已正确加载。如果它抛出一个错误Reference Error, jQuery is not defined,则没有加载 JQuery 框架。

  2. 如果 JQuery 加载正确,请尝试以下建议

    将此语句<%= javascript_include_tag 'application' %>放在 head 标记内或视图/布局文件的顶部。

    尝试使用下面的代码段将类添加到元素,最好是在页面末尾(即使在结束 HTML 标记之后也可以放置)

    <script type="text/javascript">
       $(document).ready(function() {
        $('#stat-form-inner').addClass('test-class');
       });
    </script> 
    

希望这可以帮助

于 2013-02-18T10:31:33.013 回答
1

将你的脚本放在文件夹app/assets/javascript中,确保使用$("..."),而不是$.().

欢迎来到 Rails!

于 2013-02-18T05:25:38.893 回答
0

您正在结束正文标记上方添加 javascript_include_tag。所以这意味着你的脚本是在页面加载 jquery 之前执行的。将 javascript_include_tag 调用移动到 head 标签,它应该可以工作。

于 2013-02-18T05:24:49.163 回答