如何删除单元格中的元素?

huangapple go评论70阅读模式
英文:

How delete elem in cell?

问题

Code Output after attempting to add a cell: 试图添加单元格后的代码输出:未捕获的TypeError:无法读取未定义的属性(读取'addEventListener')

let name   = document.querySelector('#name');
let price  = document.querySelector('#price');
let amount = document.querySelector('#amount');
let add    = document.querySelector('#add');
let table  = document.querySelector('#table');
let total  = document.querySelector('#total');

function createCell(tr, value, name) {
  let td = document.createElement('td')
  td.textContent = value
  td.classList.add(name)
  tr.append(td)
}

add.addEventListener('click', function() {
  let tr = document.createElement('tr');
  createCell(tr, name.value, 'name');
  createCell(tr, price.value, 'price'); 
  createCell(tr, amount.value, 'amount');
  createCell(tr, price.value * amount.value, 'cost');
  createCell(tr, 'delete', 'remove').addEventListener('click', function(ev) {
    ev.target.closest('tr').remove()
  })
  table.appendChild(tr);
  recountTotal()
});
英文:

Code Otput after atempt add cell: Uncaught TypeError: Cannot read properties of undefined (reading 'addEventListener')

let name   = document.querySelector('#name');
let price  = document.querySelector('#price');
let amount = document.querySelector('#amount');
let add    = document.querySelector('#add');
let table  = document.querySelector('#table');
let total  = document.querySelector('#total');

function createCell(tr, value, name) {
	let td = document.createElement('td')
  td.textContent = value
  td.classList.add(name)
  tr.append(td)
}

add.addEventListener('click', function() {
	let tr = document.createElement('tr');
	createCell(tr, name.value, 'name');
	createCell(tr, price.value, 'price'); 
	createCell(tr, amount.value, 'amount');
	createCell(tr, price.value * amount.value, 'cost');
	createCell(tr, 'delete', 'remove').addEventListener('click', function(ev) {
	  ev.target.closest('tr').remove()
  })
	table.appendChild(tr);
  recountTotal()
});

答案1

得分: 1

如错误信息所说,你正在尝试在未定义的值上调用 addEventListener。这意味着 createCell 没有返回任何内容。

为了解决这个问题,你需要返回你创建的 td。所以你更新后的函数应该像这样:

function createCell(tr, value, name) {
  let td = document.createElement('td')
  td.textContent = value
  td.classList.add(name)
  tr.append(td)  

  return td
}
英文:

As error says, you're trying to call addEventListener on undefined value.
It means that createCell doesn't return anything.

To resolve the issue you have to return td you've created inside.
So your updated function should look like this:

function createCell(tr, value, name) {
  let td = document.createElement('td')
  td.textContent = value
  td.classList.add(name)
  tr.append(td)  

  return td
}

huangapple
  • 本文由 发表于 2023年5月10日 19:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定