简体   繁体   English

如何检查图像是否加载并将其设置为克隆模板的背景图像

[英]How to check if image loads and set it as background-image of a cloned template

I have an HTML template I'm calling for some API and receive a list of objects我有一个 HTML 模板我正在调用一些 API 并接收对象列表

I run in loop on all objects and for each create a clone of the template:我在所有对象上循环运行,并为每个对象创建一个模板的克隆:

 const data = [{ id: 'someid', poster: 'some_image_url', url: 'some_link_url', title: 'Title', description: 'description' }] const construct = data => { const template = document.querySelector('#type1') const clone = template.content.cloneNode(true) clone.querySelector('a').setAttribute('href', data.url) clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`) clone.querySelector('.title').textContent = data.title clone.querySelector('.description').textContent = data.description return clone } data.forEach(data => document.body.appendChild(construct(data)))
 <template id="type1"> <div class='type1'> <a> <div class='poster'></div> <div class='content'> <div class='title'></div> <div class='description'></div> </div> </a> </div> </template>

So far everything works just fine.到目前为止,一切正常。 The problem begins when I decide to check if the image in the poster link is loaded, and if not - set some default image.当我决定检查poster链接中的图像是否已加载时,问题就开始了,如果没有 - 设置一些默认图像。 First I tried to do the following (instead of clone.querySelector('.poster') ):首先,我尝试执行以下操作(而不是clone.querySelector('.poster') ):

const img = new Image
img.onload = function() {
  clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
}
img.onerror = function() {
  clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
}
img.src = data.poster

And I received the following error: clone.querySelector(...) is null我收到以下错误: clone.querySelector(...) is null

I tried to use closures:我尝试使用闭包:

img.onload = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
  }
})(clone)
img.onerror = (function (clone) {
  return function () {
    clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
  }
})(clone)

Alas, same result, same error.唉,同样的结果,同样的错误。

I also tried to use .apply(clone) on the methods above, however in that case all the images were set to default image in the onerror method, even though the URL in data.poster did return an image.我还尝试在上述方法中使用.apply(clone) ,但是在这种情况下,所有图像都在onerror方法中设置为默认图像,即使 data.poster 中的data.poster确实返回了图像。

Why is this happening and how to make it work?为什么会发生这种情况以及如何使其发挥作用?

Save the poster element before the async load event handlers.在异步加载事件处理程序之前保存海报元素。 It seems the clone element is out of scope at the time of the onload of the image在加载图像时,克隆元素似乎超出了 scope

 const data = [{ id: 'someid', poster: 'https://www.freecodecamp.org/news/content/images/2021/06/w-qjCHPZbeXCQ-unsplash.jpg', url: 'some_link_url', title: 'Title', description: 'description' }] const construct = data => { const template = document.querySelector('#type1') const clone = template.content.cloneNode(true) const poster = clone.querySelector('.poster') const img = new Image() img.onload = function() { poster.setAttribute('style', `background-image: url("${data.poster}")`) console.log(poster.style.backgroundImage) } img.onerror = function() { poster.setAttribute('style', 'background-image: url("./assets/default.png")') } img.src = data.poster clone.querySelector('a').setAttribute('href', data.url) clone.querySelector('.title').textContent = data.title clone.querySelector('.description').textContent = data.description return clone } data.forEach(data => document.body.appendChild(construct(data)))
 .poster { height: 100px; width: 100px; }
 <template id="type1"> <div class='type1'> <a> <div class='poster'></div> <div class='content'> <div class='title'></div> <div class='description'></div> </div> </a> </div> </template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM