[英]My function doesn't work twice in JavaScript
I have a table with numerous rows and columns and want to change the placeholder text, 'Cell 1' and 'Cell 2' (in column 1 and 2), within the td cells to 'Success'.我有一个包含许多行和列的表格,并且想要将td单元格中的占位符文本“单元格 1”和“单元格 2”(在第 1 列和第 2 列中)更改为“成功”。
I have written a function to do this, but it only changes the first cell when I click it and no others when I try to click them.我已经编写了一个函数来执行此操作,但是当我单击它时它只会更改第一个单元格,而当我尝试单击它们时不会更改其他单元格。
document.querySelector('td').addEventListener('click', button8Click);
function button8Click() {
document.querySelector('td').innerHTML = "Success";
}
I need to specifically target the td element, and thought I did so but I am at a standstill.我需要专门针对td元素,并认为我这样做了,但我处于停滞状态。
I guess you don't know how the querySelector
works.我猜你不知道
querySelector
是如何工作的。 It selects the first td element.它选择第一个 td 元素。 This is why it only works once.
这就是它只工作一次的原因。
You need something like this:你需要这样的东西:
function changeContent(i) {
document.querySelectorAll('td')[i].innerHTML = "Success";
}
This will change the td element with the number i.这将更改编号为 i 的 td 元素。
The querySelector()
method returns the first element that matches a specified CSS selector(s) in the document. querySelector()
方法返回与文档中指定的 CSS 选择器匹配的第一个元素。 If you need to add function to all the td
elements try如果您需要向所有
td
元素添加功能,请尝试
Array.from(document.getElementsByTagName('td')).forEach(it => {it.addEventListener('click', button8Click)})
Also you need to change you function to identify which row is clicked and should be changed.您还需要更改您的功能以识别单击了哪一行并且应该更改。
function button8Click(event) {
event.target.innerHTML = "Success";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.