Rails 应用程序未显示比率 js 插件
Posted
技术标签:
【中文标题】Rails 应用程序未显示比率 js 插件【英文标题】:Rails app not showing raty js plugin 【发布时间】:2018-03-15 04:42:16 【问题描述】:我使用的是 Rails 5.0 版,使用 Raty js 时出现这些错误
jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined
at jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761
(anonymous) @ jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761
2:131 Uncaught TypeError: $(...).raty is not a function
at 2:131
我添加raty JS插件的代码如下。
<script>
$('.review-rating').raty(
readOnly: true,
score: function()
return $(this).attr('data-score');
,
path: '/assets/'
);
这与显示我的部分评论的 show.html.erb 文件相对应
<div class="review-rating" data-score="<%= review.rating %>"></div>
<p><%= review.comment %></p>
<% if user_signed_in? %>
<% if review.user_id == current_user.id %>
<%= link_to "Edit", edit_book_review_path(review.book, review) %>
<%= link_to "Delete", book_review_path(review.book, review), method: :delete, data:
confirm: "Are you sure?" %>
<% end %>
<% end %>
jQuery 肯定在应用程序中,因为我已经添加了它并且我正在为某些需要 jQuery 的元素使用引导程序,这些元素都可以正常工作。
我已将 Raty 的图像添加到 app/assets/images 路径,并将 raty js 文件添加到 javascripts 文件夹。
任何关于 Rails 不阅读 Raty 的见解???
谢谢
【问题讨论】:
【参考方案1】:看起来raty
库未加载,但您尝试对其进行初始化。将您的代码包装到$(document).ready
$(document).ready(function()
$('.review-rating').raty(
readOnly: true,
score: function()
return $(this).attr('data-score');
,
path: '/assets/'
);
);
【讨论】:
由于某种原因增加了几行额外的错误at Object.fireWith [as resolveWith] (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3363) at Function.ready (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3583) at HTMLDocument.completed (jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1:3618)
【参考方案2】:
我想通了。
首先,将此添加到您的 application.js
文件的顶部
//= require jquery3
//= require jquery_ujs
//= require jquery.raty
接下来,将 show.html.erb
视图中的 js 代码包装到 $(document).ready
中,如下所示:
$(document).ready(function()
$('.review-rating').raty(
readOnly: true,
score: function()
return $(this).attr('data-score');
,
path: '/assets/'
);
);
最后,添加
<script src="/assets/jquery.js" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js" type="text/javascript"></script>
在你上面的application.html.erb
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
这应该可以解决问题,您应该会看到评论星!
【讨论】:
以上是关于Rails 应用程序未显示比率 js 插件的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 Yarn 将 JS 插件添加到 Rails 6 应用程序