【发布时间】:2020-04-20 09:17:43
【问题描述】:
你好 stackoverflow 社区。p>
我正在尝试将多个图像模式添加到带有图像的简单 Rails 博客文章中。
我使用带有简单
posts.each循环的帖子生成器来生成帖子。 然而,当使用 javascript 创建图像模态时,.each循环生成的图像只是在模态中返回404 image not found。 为了测试,我链接了一些静态图片,并且里面的图片成功创建了模态。
我认为这与在 ruby 代码之前执行的 javascript 有关,但是我不确定。
//RUBY CODE to generate posts
<div class="projectcolumn">
<% @posts.each do |post| %>
<div class="blurbox">
<h1><%= post.title %></h1>
<p><%= post.content %></p>
<div class="postimage" id="myImg">
<%= image_tag(post.image)%>
</div>
</div>
<% end %>
//static images I used to test if the modal is working
<img class="postimage" id="myImg" src="http://onebigphoto.com/uploads/2012/10/midnight-sun-in-lofoten-norway.jpg" alt="Midnight sun in Lofoten, Norway" width="300" height="200">
<img class="postimage" id="myImg" src="http://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/1490029386/fisherman-cabin-hamnoy-lofoten-islands-norway-NORWAY0320.jpg?itok=cpPuUjh1" alt="Fishermen's cabins in Lofoten, Norway"
width="300" height="200">
<img class="postimage" id="myImg" src="http://fjordtours.blob.core.windows.net/fjordtours-umbraco/1199/gerirangerfjord-per-ottar-walderhaug-fjordnorway.jpg" alt="Gerirangerfjord, Norway" width="300" height="200">
//the modal div
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
</div>
<script>// create references to the modal...
var modal = document.getElementById('myModal');
// to all images -- note I'm using a class!
var images = document.getElementsByClassName('postimage');
// the image in the modal
var modalImg = document.getElementById("img01");
// and the caption in the modal
var captionText = document.getElementById("caption");
// Go through all of the images with our custom class
for (var i = 0; i < images.length; i++) {
var img = images[i];
// and attach our click listener for this image.
img.onclick = function(evt) {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
</script>
我认为通过将脚本标签放在 index.html.erb 文件的末尾,javascript 将在图像全部构建后编译。这种思路有缺陷吗?
【问题讨论】:
标签: javascript ruby-on-rails image modal-dialog simplemodal