如何将IMG URL从构造函数传递到函数,然后创建/附加图像



我有一个卡类,将URL作为参数以及其他几个参数。CreateCard函数根据参数创建卡。如何根据URL输入来创建和附加卡中的图像?

更新:重新设计代码并获得了正确的结果。我如何将其完善为最有效的?

<section id="shootout" class="memory-game">
</section>
const game = document.getElementById('shootout')
class Card {
  constructor(name, imgUrl, health, ammo) {
    this.name = name
    this.health = health
    this.ammo = ammo
    this.imgUrl = imgUrl
  }
  createCard(imgUrl) {
    let card = document.createElement('div')
    card.className = this.name
    card.dataset.health = this.health
    card.dataset.ammo = this.ammo
    const addImages = () => {
      let frontFace = new Image()
      frontFace.src = this.imgUrl
      frontFace.className = 'front-face'
      let backFace = new Image()
      backFace.src = 'img/card-back.svg'
      backFace.className = 'back-face'
      card.append(backFace)
      card.append(frontFace)
    }
    addImages()
    game.appendChild(card)
  }
}
// Test Card Instance
const testCard = new Card('ammunition', 'img/react.svg', 1, null).createCard()

更新的代码:

class Card {
  constructor(name, imgUrl, health, ammo) {
    this.name = name
    this.health = health
    this.ammo = ammo
    this.imgUrl = imgUrl
    this.addImages = (card) => {
      let frontFace = new Image()
      frontFace.src = this.imgUrl
      frontFace.className = 'front-face'
      let backFace = new Image()
      backFace.src = 'img/card-back.svg'
      backFace.className = 'back-face'
      card.append(backFace)
      card.append(frontFace)
    }
  }
  createCard(imgUrl) {
    let card = document.createElement('div')
    card.className = this.name
    card.dataset.health = this.health
    card.dataset.ammo = this.ammo
    this.addImages(card)
    game.appendChild(card)
  }
}

我能够通过将卡变量传递给卡类构造函数中的Addimages方法来获得所需的结果。

class Card {
  constructor(name, imgUrl, health, ammo) {
    this.name = name
    this.health = health
    this.ammo = ammo
    this.imgUrl = imgUrl
    this.addImages = (card) => {
      let frontFace = new Image()
      frontFace.src = this.imgUrl
      frontFace.className = 'front-face'
      let backFace = new Image()
      backFace.src = 'img/card-back.svg'
      backFace.className = 'back-face'
      card.append(backFace)
      card.append(frontFace)
    }
  }
  createCard(imgUrl) {
    let card = document.createElement('div')
    card.className = this.name
    card.dataset.health = this.health
    card.dataset.ammo = this.ammo
    this.addImages(card)
    game.appendChild(card)
  }
}

最新更新