【问题标题】:Display data on html template tag from javascript从 javascript 在 html 模板标签上显示数据
【发布时间】:2020-11-13 14:01:34
【问题描述】:

我正在尝试从 javascript 向 html 模板标签显示数据。我可以将图像从 javascript 显示到模板,但是当我在 p 标签中尝试同样的事情时,它给了我一个错误 TypeError: Cannot set property 'innerText' of null。没有任何效果,我尝试使用 text/textContent/inner/innerHTML。我在这里有什么遗漏吗?

index.html

<template id="product-template">
    <div class="col-sm-4">
      <div class="card border-light">
        <ul class="list-group list-group-flush">
          <li class="list-group-item"><img class="card-img-top" src="" id="product-img"></li>
          <li class="list-group-item"><p id="product-name">Name: </p></li>
          <li class="list-group-item"><p id="product-brand">Brand: </p></li>
          <li class="list-group-item"><p id="product-price">Price: </p></li>
          <li class="list-group-item"><p id="product-description">Description: </p></li>
        </ul>
      </div>
    </div>
</template>


<div class="container">
  <h1>Shop Online</h1>
  <div id="appRoot" class="row"></div>
</div>

script.js

const template = document.getElementById('product-template');
const card = document.querySelector('#appRoot');
length=8;
for(let index=0; index<length; index++){
  var clone = template.content.cloneNode(true);
  var image = clone.querySelector("li");
  var path = "/images/"
  image.querySelector("#product-img").src = path + data.imagepath;
  var name = clone.querySelector('p');
  name.querySelector('#product-name').innerText = data.name;
  card.appendChild(clone);

【问题讨论】:

    标签: javascript html templates dom


    【解决方案1】:

    您可能不需要查询 p 标签,因为无论如何您都在下一行通过 id 来获取它们。

    var name = clone.querySelector('p');
    name.querySelector('#product-name').innerText = data.name;
    

    如果您理解我的话,该代码似乎正在寻找类似的内容:

    <li class="list-group-item"><p><p id="product-name">Name:</p></p></li>
    

    innerText 为空,因为&lt;p&gt; 标签内没有 ID 为“产品名称”的标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 2022-08-23
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多