使用Ajax创建图像



我使用的是Bootstrap主题,我希望通过AJAX加载主题图像显示页面上的图像库。照片是带有AJAX的JSON,但我无法将它们显示在页面上。

这个主题的画廊相关部分来自原始JS文件:

var productGallery = function () {
var gallery = document.querySelectorAll('.product-gallery');
if (gallery.length) {
var _loop8 = function _loop8(i) {
var thumbnails = gallery[i].querySelectorAll('.product-gallery-thumblist-item'),
previews = gallery[i].querySelectorAll('.product-gallery-preview-item');
for (var n = 0; n < thumbnails.length; n++) {
thumbnails[n].addEventListener('click', changePreview);
} // Changer preview function
function changePreview(e) {
e.preventDefault();
for (var _i3 = 0; _i3 < thumbnails.length; _i3++) {
previews[_i3].classList.remove('active');
thumbnails[_i3].classList.remove('active');
}
this.classList.add('active');
gallery[i].querySelector(this.getAttribute('href')).classList.add('active');
}
};
for (var i = 0; i < gallery.length; i++) {
_loop8(i);
}
}
}();

使用Ajax的JSON文件中的数据:

some AJAX code..
if (slidePhotos.photos) {
for (let x= 0; x< slidePhotos.photos.length; x++) {
document.getElementById('gallery_photos_div').innerHTML += '<div class="product-gallery-preview-item" id="' + x+ '"><img src="' + slidePhotos.photos[x].url + '" alt=""></div>';
document.getElementById('gallery_thumbs_div').innerHTML += '<a class="product-gallery-thumblist-item" href="#' + x+ '"><img src="' + slidePhotos.photos[x].url + '"></a>';
}
}

HTML代码已经生成,但不幸的是,当我点击它时,图像没有改变

示例JSON:

[
{
"url":"https://example.com/image1.jpg",
"url":"https://example.com/image2.jpg"
}
]

你能告诉我哪里出了错吗?

我在这里看到了几个问题:

  • 看起来,您用来用JSON文件中的新图像填充幻灯片的代码会将div.product-gallery-preview-item附加到幻灯片容器中,但不会附加相应的.product-gallery-thumblist-item。在productGallery函数中,click处理程序绑定到后者,而不是前者。您需要确保添加了这些目标缩略图元素以及预览元素
  • 假设productGallery函数是在第一次加载page/DOM以初始化幻灯片放映时启动的。控制幻灯片放映功能的click事件处理程序仅绑定到函数运行时出现的元素。如果您在通过AJAX附加内容时没有重复运行此函数(我希望您没有,因为这会将重复的事件处理程序绑定到幻灯片中已经存在的元素(,那么您需要确保您的新元素已经准备好以与现有元素相同的方式响应click。这里有几个选项:
    • 重构productGallery,使其可以在同一幻灯片中重复调用,例如:在.product-gallery-thumblist-item.product-gallery-preview-item查询选择器的末尾添加:not(.slideshow-processed),然后在绑定事件处理程序后将slideshow-processed类添加到这些元素中,以便在后续调用productGallery时不会再次处理它们
    • 重构productGallery以使用事件委派(其中父元素侦听其子元素上发生的事件(。这将允许您将事件处理程序绑定到.product-gallery容器一次,并为附加到幻灯片中的任何预览/缩略图对启动它,而无需重新调用productGallery。有关活动委派的更多信息,请访问https://javascript.info/event-delegation.

希望这能为你指明正确的方向。编码快乐!

最新更新