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
Add a ment  | 

4 Answers 4

Reset to default 6

This 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