如何在javascript中设置rails背景图像url?

如何在javascript中设置rails背景图像url?,javascript,jquery,html,css,ruby-on-rails,Javascript,Jquery,Html,Css,Ruby On Rails,在我的rails应用程序中,我有一些内容和图像按钮(每个内容都有一个图像)。当用户单击按钮时,我想显示相应的图像 在我的项目中,我将所有图像保存在assets/images/preview/id1.png下(例如)。在我的javascript代码中,单击查看内容按钮时,我希望更改背景图像以显示相应的图像。我想根据分配给该按钮的id查找图像。我怎样才能做到这一点 如何为背景图像设置该图像url: _page2.html.erb <div class="content"> <tab

在我的rails应用程序中,我有一些内容和图像按钮(每个内容都有一个图像)。当用户单击按钮时,我想显示相应的图像

在我的项目中,我将所有图像保存在assets/images/preview/id1.png下(例如)。在我的javascript代码中,单击查看内容按钮时,我希望更改背景图像以显示相应的图像。我想根据分配给该按钮的id查找图像。我怎样才能做到这一点

如何为背景图像设置该图像url:

_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>
JSFIDLE中的链接:

在content/preview.js中

$('.view').click(function (event){
     var image = $(this).id
   $(this).css("background", "url(image.jpg) no-repeat");
    });
    });
$('.view').click(function (event){
    $(this).css("background", "url(sample.png) no-repeat");
    });
我尝试使用上面列出的代码。图像似乎未加载,因为它在content/sample.png而不是assets/images/sample.png中搜索图像

试试这个

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

在您的情况下,如果希望根据元素的
id
设置背景,只需修改如下代码:

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

感谢您通过删除url“url(assets/“+id+”.png)中的图像(无重复)而完成的出色工作);