如何使用 HTML 字符串中 foreach 方法的数据调用函数?

How to call a function with data from foreach method in HTML string?

我正在从数组中生成一些 html 卡片和按钮。我想用 foreach 中的数据调用一个函数。但是我好像想不通。

我在 renderProducts() 方法中遇到问题。

/// <reference path="coin.ts" />
/// <reference path="product.ts" />
/// <reference path="productFactory.ts" />

enum VendingMachineSize {
  small = 6,
  medium = 9,
  large = 1,
}

class Cell {
  constructor(public product: CocoCola) {}
  stock: 3;
  sold: false;
}

class VendingMachine {
  private totalMoney = 0;
  private totalMoneyText = <HTMLSpanElement>document.getElementById("total-money");
  private containerElement = <HTMLDivElement>document.querySelector(".machine");
  allCoins: number[] = [0];
  cells = [];
  selectedCells = [new Cell(new CocoCola())];

  set size(givenSize: VendingMachineSize) {
    this.cells = [];

    for (let index = 0; index < givenSize; index++) {
      let product = ProductFactory.GetProduct();
      this.cells.push(new Cell(product));
    }
    this.renderProducts();
  }

  constructor() {
    console.log("I am vending machine!");
  }

  select(cell: Cell) {
    cell.sold = false;
    this.selectedCells.push(cell);
    console.log(this.selectedCells);
  }

  acceptCoin(coin: Quarter): void {
    this.totalMoney += coin.Value;
    this.totalMoneyText.textContent = this.totalMoney.toString();
  }

  renderProducts() {
    this.cells.forEach((product) => {
      let html = `<div class="card " style="width: 18rem">
        <img src=${product.product.category.getImageUrl()} class="" alt="..." />
        <div class="card-body">
          <h5 class="card-title">${product.product.name}</h5>
          <p class="card-text">
           ${product.product.description}
          </p>
          <button type="button" class="btn btn-outline-dark w-100 select-btn"  onclick="machine.select(${product})"> ${
        product.product.price
      }</button>
        </div>
      </div>`;
      this.containerElement.insertAdjacentHTML("beforeend", html);
    });
  }
}

<button type="button" class="btn btn-outline-dark w-100 select-btn" onclick="machine.select(${product})"> ${product.product.price}</button> 我希望这个按钮有一个参数为 product

的 onclick 侦听器

当我这样做时,它给我这个错误:Uncaught SyntaxError: Unexpected identifier (at (index):33:63)

这是我创建 class

实例的地方
/// <reference path="vendingMachine.ts" />

const machine = new VendingMachine();
machine.size = VendingMachineSize.medium;

你不能那样做,因为你使用了字符串插值。

当您键入时

`some text ${product}`

product 是您范围内的对象,javascript 将调用对象上的 toString 方法和 returns [Object object] <- 这是错误您收到了:**Uncaught SyntaxError: Unexpected identifier**

当您尝试插入 onclick 处理程序时,您应该生成有效的 JS 代码,例如:

<div onclick="machine.select(${number})"></div>,
<div onclick="machine.select('${string}')"></div>,
<div onclick="machine.select(JSON.parse('${JSON.encode(product)}'))"></div>

我推荐生成后设置监听器html; 例如:

<button type="button" data-product="${product.product.name}" class="btn btn-outline-dark w-100 select-btn"> ${product.product.price}</button>
...
this.containerElement.insertAdjacentHTML("beforeend", html);
this.containerElement.querySelectorAll('button').forEach(item => {
  item.addEventListener('click', () => {
    this.select(item.dataset.product)
  })
})