我正在從陣列中生成一些 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 style="width: 18rem">
<img src=${product.product.category.getImageUrl()} alt="如何使用 HTML 字串中的 foreach 方法中的資料呼叫函式?" />
<div >
<h5 >${product.product.name}</h5>
<p >
${product.product.description}
</p>
<button type="button" onclick="machine.select(${product})">?? ${
product.product.price
}</button>
</div>
</div>`;
this.containerElement.insertAdjacentHTML("beforeend", html);
});
}
}
<button type="button" onclick="machine.select(${product})">?? ${product.product.price}</button>我希望這個按鈕有一個帶有產品引數的 onclick 監聽器
當我這樣做時,它給了我這個錯誤: Uncaught SyntaxError: Unexpected identifier (at (index):33:63)
這是我創建類實體的地方
/// <reference path="vendingMachine.ts" />
const machine = new VendingMachine();
machine.size = VendingMachineSize.medium;
uj5u.com熱心網友回復:
你不能那樣做,因為你使用字串插值。
當您鍵入
`some text ${product}`
并且product是您范圍內的物件,javascript 將呼叫toString物件上的方法并回傳[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)
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471694.html
標籤:javascript html 打字稿 循环 哎呀
