如何连续添加多个<td> JavaScript

时间:2019-09-04 10:58:15

标签: javascript object innerhtml

const list = document.querySelector('#book');
const row = document.createElement('tr');

>     row.innerHTML ='
>     <td>${book.title}</td>
>     <td>${book.author}</td>
>     <td>${book.number}</td>
>     <td><a href="#" class="btn btn-danger btn-smdelete">X</a></td>
>                     ';

list.appendChild(row);

问题是为什么我不能使用该方法在 tr 中添加多个 td ,但出现错误,如何解决?我知道使用insertRow() then create insertCell()的另一种方法,但我不想使用它。

1 个答案:

答案 0 :(得分:0)

var books = [{
  title: "IT",
  author: "Stephen King",
  number: "0987654321"
}, {
  title: "Pet Sematary",
  author: "Stephen King",
  number: "1234567890"
}]

const list = document.querySelector('#book');

books.forEach(function(book) {
  const row = document.createElement('tr');
  const tdBook = document.createElement('td');
  const tdAuthor = document.createElement('td');
  const tdNumber = document.createElement('td');
  const tdLink = document.createElement('a');

  tdBook.innerText = book.title;
  tdAuthor.innerText = book.author;
  tdNumber.innerText = book.number;
  tdLink.href = "#";
  tdLink.classname = "btn btn-danger btn-smdelete";
  tdLink.innerText = "X";

  row.appendChild(tdBook);
  row.appendChild(tdAuthor);
  row.appendChild(tdNumber);
  row.appendChild(tdLink);

  list.appendChild(row);
});
<table id="book">

</table>