簡體   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