简体   繁体   中英

how to set rails background image url in javascript?

In my rails application, I have some set of content and image-button (each piece of content has an image). When a user clicks the button, I want to show the respective image.

In my project, I saved all my images under assets/images/preview/id1.png (for example). In my javascript code, when clicking the view-content button i want to change the background image to display the respective image. I want to lookup the image based on the id assigned to that button. How can I achieve this?

How to set that image url for back ground image:

_page2.html.erb

<div class="content">
<table>
    <tr>
        <td>    content about the image    </td>
        <td> <div id="<%= content[:lable].delete(' ')%>" class="view"> VIEW-IMAGE</div></td>
    </tr>
    <tr>
        <td>content about the image</td>
        <td><div id= "<%= content[:lable].delete('')%>" class="view">VIEW-IMAGE</div></td>
    </tr>
</table>

content/preview.js

$('.view').click(function (event){
     var image = $(this).id
   $(this).css("background", "url(image.jpg) no-repeat");
    });
    });

link in Jsfiddle: http://jsfiddle.net/bkrx2rxz/1/

In content/preview.js

$('.view').click(function (event){
    $(this).css("background", "url(sample.png) no-repeat");
    });

I tried using the code listed above. It appears the image is not loaded because it searches images in content/sample.png instead of assets/images/sample.png.

Try this

$('.view').click(function (event){
    $(this).css("background", "url(assets/images/sample.png) no-repeat");
    });

EDIT

In your case if you wish to set the background according to id of the element, simply modify the code like this:

$('.view').click(function (event){
  var id = $(this).attr('id');
  $(this).css("background", "url(assets/images/" + id + ".png) no-repeat");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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