繁体   English   中英

如何在JavaScript中设置Rails背景图片网址?

[英]how to set rails background image url in javascript?

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

在我的项目中,我将所有图像保存在asset / images / preview / id1.png下(例如)。 在我的javascript代码中,当单击查看内容按钮时,我想更改背景图像以显示相应的图像。 我想根据分配给该按钮的ID查找图像。 我该如何实现?

如何为背景图片设置该图片网址:

_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>

内容/ preview.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中的图片,而不是资产/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");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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