[英]How can I use Javascript in a partial in rails?
我试图通过使用AJAX在Rails中渲染部分片段来创建一个弹出窗口。 弹出窗口工作正常,但是我的Javascript似乎没有任何作用。
这本质上就是我的代码。
javascript
$(document).ajaxSuccess(function(event, xhr, settings) {
$(xhr.responseText).appendTo('body').modal();
});
$('.flexslider').flexslider({
animation: "slide"
});
弹出
.col-md-6
.flexslider
%ul.slides
%li
%img(src="http://g-ecx.images-amazon.com/images/G/01/kindle/dp/2013/KT/feature-cs._V355642982_.jpg")
%li
%img(src="http://g-ecx.images-amazon.com/images/G/01/kindle/dp/2013/KT/feature-camera._V355723652_.jpg")
%li
%img(src="http://g-ecx.images-amazon.com/images/G/01/kindle/dp/2013/KT/feature-wifi._V355643083_.jpg")
%li
%img(src="http://g-ecx.images-amazon.com/images/G/01/kindle/dp/2013/KT/feature-cs._V355642982_.jpg")
控制者
render partial: 'product', locals: {product: @product}, layout: false if request.xhr?
我认为您的JS可能需要从dom就绪块中调用才能工作。
这是我以方便的方式包括js的工作。 在我的布局中,我产生了两个代码块:一个用于javascript标签,一个用于在dom ready块中运行的代码。 所以我的布局看起来像这样:
#at the bottom of the body tag (inside it)
<%= yield :javascript_includes %>
<script type="text/javascript">
$(function() {
<%= yield :jquery_ready %>
});
</script>
这使我能够像这样将JS添加到我的局部和模板中:
<% content_for :javascript_includes do %>
<% javascript_include tag "someLibrary.js" %>
<% end %>
和/或
<% content_for :jquery_ready do %>
$("#foo").click(function(){ doStuff()});
<% end %>
这些包括可以在模板/部分中的任何位置完成,但我的惯例是始终将它们放在顶部,以使其更加明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.