Javascript object not working in innerHTML

问题: I'm currently practicing objects and properties using JavaScript. I tried inserting it in innerHTML but the desired output is displaying ${item.img} in string form instead...

问题:

I'm currently practicing objects and properties using JavaScript. I tried inserting it in innerHTML but the desired output is displaying ${item.img} in string form instead of the actual image. I also tried separating the code in different lines in notepad++, but it is not recognized by the compiler unless it is typed in one line. Kindly advice solution for this.

Here is the JavaScript code:

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>';

回答1:

According to the syntax, Template Literals are enclosed by the back-tick (``). Since you are using single quote (' ') the whole string is treating as plain string, it is not evaluating the expression in it.

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>`;
  • 发表于 2019-03-12 06:51
  • 阅读 ( 166 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除