如何在foreach中调用函数?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在foreach中调用函数?相关的知识,希望对你有一定的参考价值。
我在小图片上添加了一个eventListener
,当点击一张图片时,PhotoSwipe打开整个画廊,但它没有提醒开...
如果我在js文件的末尾取消注释//openPhotoSwipe()
,则在加载页面时会出现PhotoSwipe库,并且eventListener
按预期工作。但这不是我想要的......我是javascript的新手......非常感谢帮助和解释
function openPhotoSwipe()
var pswpElement = document.querySelectorAll('.pswp')[0];
var pics = Array.from(document.getElementsByTagName('img'));
var items = []
pics.forEach(function(e)
items.push(src: e.src, w: 0, h: 0);
)
var options =
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0,
closeOnScroll: false,
closeOnClick: false,
;
var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.listen('gettingData', function(index, item)
if (item.w < 1 || item.h < 1)
var img = new Image();
img.onload = function()
item.w = this.width;
item.h = this.height;
gallery.invalidateCurrItems();
gallery.updateSize(true);
img.src = item.src;
);
gallery.init();
;
var open = Array.from(document.getElementsByClassName("open_gallery"));
open.forEach(function(e)
e.addEventListener('click', openPhotoSwipe);
)
// openPhotoSwipe();
这是我观点的一部分:
<div class="container">
<h1><%= @article.title %></h1>
<p><%= @article.description %></p>
<div class="thumb_images">
<% @article.attachments.each do | art| %>
<%= link_to image_tag art.url, class: "open_gallery" %>
<% end %>
</div>
</div>
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<% @article.attachments.each do | art| %>
<div class="pswp__item">
<%= image_tag art.url %>
</div>
<% end %>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut">
</div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip">
</div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center">
</div>
</div>
</div>
</div>
</div>
答案
正如您在comment中确认我的猜测是正确的,您的link_to基本上没有创建所需的html标记。所以我在这里把comment作为答案。写下您的方法链接如下:
<%= link_to "#", class: "open_gallery" do %>
<%= image_tag art.url %>
<%end%>
以上是关于如何在foreach中调用函数?的主要内容,如果未能解决你的问题,请参考以下文章
jsp页面中如何实现<c:forEach>循环一次就调用一次js函数?