简体   繁体   English

如何在Rails的局部中使用Javascript?

[英]How can I use Javascript in a partial in rails?

I am trying to put a slider a popup that I am creating by rendering a partial in rails with AJAX. 我试图通过使用AJAX在Rails中渲染部分片段来创建一个弹出窗口。 The popup is working just fine, but my Javascript does not seem to be having any effect. 弹出窗口工作正常,但是我的Javascript似乎没有任何作用。

This is essentially the code I have. 这本质上就是我的代码。

javascript javascript

$(document).ajaxSuccess(function(event, xhr, settings) {
    $(xhr.responseText).appendTo('body').modal();
});
$('.flexslider').flexslider({
    animation: "slide"
});

popup 弹出

.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")

controller 控制者

render partial: 'product', locals: {product: @product}, layout: false if request.xhr?

I think your JS may need to be called from a dom ready block in order to work. 我认为您的JS可能需要从dom就绪块中调用才能工作。

This is what I do to include js in a convenient way. 这是我以方便的方式包括js的工作。 In my layout i yield to two code blocks: one for javascript tags and one for code to run in the dom ready block. 在我的布局中,我产生了两个代码块:一个用于javascript标签,一个用于在dom ready块中运行的代码。 So my layout looks like this: 所以我的布局看起来像这样:

#at the bottom of the body tag (inside it)

<%= yield :javascript_includes %>

<script type="text/javascript">
  $(function() {
     <%= yield :jquery_ready %> 
  });   
</script>   

This enables me to do add JS to my partials and templates like so: 这使我能够像这样将JS添加到我的局部和模板中:

<% content_for :javascript_includes do %>
  <% javascript_include tag "someLibrary.js" %>
<% end %>

and/or 和/或

<% content_for :jquery_ready do %>
  $("#foo").click(function(){ doStuff()});
<% end %>

These includes can be done anywhere in the templates/partials but my convention is to always put them at the top, to make them more obvious. 这些包括可以在模板/部分中的任何位置完成,但我的惯例是始终将它们放在顶部,以使其更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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