admin管理员组文章数量:1303353
I have a jquery function that's supposed to change the background of the page. I want the background to be an image in the app/assets/images directory. However, I'm confused as to the proper way to reference the image with the asset pipeline.
Here's the line I have now:
$('body').css("background-image", "url('wele.png')");
What's the best way to access the image in the url parameter?
I have a jquery function that's supposed to change the background of the page. I want the background to be an image in the app/assets/images directory. However, I'm confused as to the proper way to reference the image with the asset pipeline.
Here's the line I have now:
$('body').css("background-image", "url('wele.png')");
What's the best way to access the image in the url parameter?
Share Improve this question asked Jan 4, 2013 at 20:36 MasonMason 7,10317 gold badges73 silver badges115 bronze badges 2-
1
What is wrong with the method you are currently using? Put the path relative to the page in between the parentheses:
url('app/assets/images/wele.png')
– user1726343 Commented Jan 4, 2013 at 20:44 - Do you have the gem "jquery-rails"? – im_benton Commented Jan 4, 2013 at 20:45
4 Answers
Reset to default 6This is covered in the documentation:
http://guides.rubyonrails/asset_pipeline.html#coding-links-to-assets
You should use the methods described in "2.3.3 JavaScript/CoffeeScript and ERB", which would mean adding the .erb extension to your JS file, and using asset_path.
Another approach that's more elegant would be to move your image to a class definition in a css.scss file and then adding that class in your jQuery:
.wele {
background-image: url(image-path('wele.png'));
}
and in your jQuery:
$('body').addClass("wele");
Try this:
$('body').css("background-image", "url('/assets/wele.png')");
In order to access assets in the pipeline, you have to specify the assets
folder.
I've been trying to find where I read this, but Rails basically converts all asset helper urls to something like /assets/asset.png
or like /assets/stylesheet.css
so you should be able to do the same by just specifying the assets
folder in your source url.
$('body').css("background-image", "url('/app/assets/images/wele.png')");
?
Assuming app is at the document root.
In my opinion, You need to use the .erb (embedded ruby) extension to allow rails path helpers in your .js files. If your js file (balabala.js for example) is in asset/javscripts/, change its name to balabala.js.erb, and then use:
$('body').css({"background-image":"<%= asset_path({'filenamehere.png') %>"});
Require this file in your asset/javscripts/application.js
//= require balabala
Then it should work
本文标签: javascriptReference rails image in jquery functionStack Overflow
版权声明:本文标题:javascript - Reference rails image in jquery function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741732970a2394930.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论