简体   繁体   English

Rails和JQuery从数组中选择一个随机项目

[英]Rails and JQuery selecting a random item from an array

I feel like I'm pretty close here trying to select a random image from my assets path and set it as the background. 我觉得我在这里很近,试图从资产路径中选择一个随机图像并将其设置为背景。

birds = ['birdonbranch.jpeg', 'birdsfighting.jpg', 'cranes.jpg', 'rainbowbird.jpeg', 'whitebird.jpeg'];
birdSample = birds.sample
$("html").css({"background-image":"url(" + "<%= asset_path(" + birdSample + ") %>" + ")"});

Wrap the first two lines in <%...%> 将前两行换成<%...%>

But you might look into http://reactrb.org which allows you to develop in straight Ruby. 但是您可以浏览http://reactrb.org ,它允许您使用纯Ruby进行开发。 Much less confusing IMHO 恕我直言

If this is a .js.erb file, your ruby code should be wrapped in <% %> . 如果这是一个.js.erb文件,则您的ruby代码应包装在<% %>

<% 
  birds = ['birdonbranch.jpeg', 'birdsfighting.jpg', 'cranes.jpg', 'rainbowbird.jpeg', 'whitebird.jpeg'];
  birdSample = birds.sample
%>

$("html").css({
  "background-image": url("<%= asset_path(birdSample) %>")
});

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

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