簡體   English   中英

Javascript對象在innerHTML中不起作用

[英]Javascript object not working in innerHTML

我目前正在使用JavaScript練習對象和屬性。 我嘗試在innerHTML中插入它,但是所需的輸出是以字符串形式而不是實際圖像顯示${item.img} 我也嘗試在notepad ++中分隔不同行中的代碼,但編譯器無法識別它,除非它在一行中鍵入。 請為此提供建議解決方案。

這是JavaScript代碼:

const item = {};
item.img = 'img-cart${partPath}';
let name = event.target.parentElement.parentElement.nextElementSibling
                .children[0].children[0].textContent;
item.name = name;
let price = event.target.parentElement.parentElement.nextElementSibling
                .children[0].children[1].textContent;
let finalPrice = price.slice(1).trim();
item.price = finalPrice;

const cartItem = document.createElement("div");
cartItem.classList.add(
    "cart-item",
    "d-flex",
    "justify-content-between",
    "text-capitalize",
    "my-3"
);      

problem is here ----> cartItem.innerHTML = '<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt=""><div class="item-text"><p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p><span>$</span><span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span></div><a href="#" id="cart-item-remove" class="cart-item-remove"><i class="fas fa-trash"></i></a></div>';

根據語法, 模板文字被后面的勾號(``)括起來。 由於您使用的是單引號(''),因此整個字符串被視為純字符串,它不會在其中評估表達式。

cartItem.innerHTML = `<img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt=""><div class="item-text"><p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p><span>$</span><span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span></div><a href="#" id="cart-item-remove" class="cart-item-remove"><i class="fas fa-trash"></i></a></div>`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM