英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论