javascript - 通过 javascript 接收 Carrierwave URL
问题描述
有没有办法通过 sql 或 javascript 来获取 Model.image_url ?
我有一个选择,当更改时,我希望<img src=>
动态更改。
在其他情况下,我执行了以下操作来更改 div 容器的背景颜色:
<%= f.grouped_collection_select :color_id, @other_model, :colors, :title, :id, :title, include_blank: "Select Color" %>
<div id="div" style="background-color:<%= "#{model.color.hex}" %>;">
...
</div>
**javascript**
var colors = <%= Color.pluck(:id, :hex).to_h.to_json.html_safe %>;
document.getElementById("model_color_id").addEventListener("change", function(){
document.getElementById("div" %>").style.backgroundColor = colors[this.value];
}, false);
为了获得载波图像,我尝试了类似的方法:
var product_mock = <%= Item.pluck(:id, :image).to_h.to_json.html_safe %>;
document.getElementById("model_item_id").addEventListener("change", function(){
document.getElementById("item").src = product_mock[this.value];
}, false);
但这并没有抓住*.url'
or*_url
尝试了这样的方法onchange
:
$('#shop_product_item_id').on('change', function(){
let item_id = $(this).val(); #tried with and without these 2 lines and with var
console.log(item_id); #tried with and without these 2 lines
var image = <%= Item.find(1).image_url %>;
document.getElementById("id").src = image;
});
有一个id:1
没有任何东西打印到控制台,但出现以下错误:
Uncaught TypeError: e.unique is not a function
有没有办法从carrierwave thorugh sql甚至javascript中的ruby中获取这个?
解决方案
您可以将代码更改Item.pluck(:id, :image).to_h.to_json.html_safe
为Item.all.map{|item| [item.id, item.image_url]}.to_h.to_json.html_safe
. 但正如其他人在评论中所说,最好通过 Ajax 请求获取项目,而不仅仅是将它们存储在 html 中。
推荐阅读
- git - 如何通过编程在bitbucket/GitHub中提交和推送代码
- python - 管理 dask localcluster 上的 worker 内存
- android - 编译渲染脚本错误“llvm-rs-cc 以非零退出值 127 完成”
- gooddata - GoodData UI 中关于 AttributeFilter 的问题
- java - Android Studio - Java - MediaPlayer 音效有时不起作用
- excel - 循环直到行中的最后一列并填充组合框
- google-cloud-platform - 数据存储模式下的 Cloud Firestore - 是否不再需要分片计数器?
- excel - 在字符串中查找子字符串,但从右到左查找excel
- python-3.x - 不再能够在 Vscode 中执行 python 代码
- python - 如何找到float64中一列和另一列的两列熊猫数据框之间的相关性是对象(字符串)