在我的 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>
内容/预览.js
$('.view').click(function (event){
var image = $(this).id
$(this).css("background", "url(image.jpg) no-repeat");
});
});
Jsfiddle 中的链接:http://jsfiddle.net/bkrx2rxz/1/
在 content/preview.js 中
$('.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");
});
关于javascript - 如何在javascript中设置rails背景图片url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28039290/