[英]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). 在我的Rails应用程序中,我有一些内容和图像按钮(每个内容都有一个图像)。 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). 在我的项目中,我将所有图像保存在asset / images / preview / id1.png下(例如)。 In my javascript code, when clicking the view-content button i want to change the background image to display the respective image.
在我的javascript代码中,当单击查看内容按钮时,我想更改背景图像以显示相应的图像。 I want to lookup the image based on the id assigned to that button.
我想根据分配给该按钮的ID查找图像。 How can I achieve this?
我该如何实现?
How to set that image url for back ground image: 如何为背景图片设置该图片网址:
_page2.html.erb _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 内容/ 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/ Jsfiddle中的链接: http : //jsfiddle.net/bkrx2rxz/1/
In content/preview.js 在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.
由于未搜索图片,因为它搜索的是content / sample.png中的图片,而不是资产/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: 如果您希望根据元素的
id
设置背景,只需修改以下代码即可:
$('.view').click(function (event){
var id = $(this).attr('id');
$(this).css("background", "url(assets/images/" + id + ".png) no-repeat");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.