繁体   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