我在 Flask 应用程序中建立了一个画廊。出于加载目的,网页会加载缩略图。我正在尝试使用 Javascript 来允许用户单击缩略图并查看完整图像。我遇到的问题是 javascript 似乎只适用于<div id="image_con"></div>. 如何让该函数适用于 div 的所有实例?或者这甚至可能与我设置事物的方式有关吗?HTML:{% block content %}{% for x in names %}<div class="date_con"> <h2>{{ x }}</h2> {% for y in names[x] %} <div class="event_con"> <span class="event_data">{{ y['date_parsed'] }}</span> <span class="event_data">{{ y['title'] }}</span> </div> <div class="image_con" id="image_con"> {% for w in y['thumbs'] %} <img class="image_small" src="{{ url_for('static', filename='thumbnails/' + w + '')}}" alt="{{ y['id'] }}"> {% endfor %} </div> <div class="cover" id="{{ y['id'] }}"> {% for z in y['fulls'] %} <img class="image_big" id="{{ z }}" style="display: none;" onclick="EventHandler(this.id)" src="{{ url_for('static', filename='gallery/' + z + '')}}" alt="error"> {% endfor %} </div> {% endfor %}</div>{% endfor %}{% endblock content %}Javascript:var hit = false,image_small = document.getElementById('image_con'),active = null;image_small.onclick = function (e) { var i = 0, tgt = e.target, items; if (tgt === this) return; items = children(image_small); var id = tgt.getAttribute('alt'); console.log(id); while (tgt.parentNode !== this) tgt = tgt.parentNode; while (items[i] !== tgt) i++; // activate the image var tar = document.getElementById(id).children; tar[i].style.display = 'block'; document.getElementById(id).style.display = 'block'; output('index : ' + i); // helpers document.getElementsByTagName('body')[0].style.overflow = 'hidden'; document.getElementsByClassName('cover')[0].style.display = 'flex';};function children(el) { var i = 0, children = [], child; while (child = el.childNodes[i++]) { if (child.nodeType === 1) children.push(child); } return children;};function output(s) { console.log(s);};
3 回答
FFIVE
TA贡献1797条经验 获得超6个赞
为确保每个图像都有一个侦听器,请尝试将侦听器添加到父级,image_con而不是每个图像。
document.getElementById('image_con').addEventListener('click', event => {
const { target } = event;
if (target.classList.contains('image_small')) {
/**
* the rest of the click handler goes here
*/
}
});
添加回答
举报
0/150
提交
取消