【发布时间】:2022-01-02 12:21:57
【问题描述】:
我想制作一个动态表格视图,在该视图中单击按钮以显示表格行,但是,当我尝试更改按钮的文本时出现错误。
window.onload = () => {
const buttons = document.getElementsByTagName("button")
console.log(buttons)
const info = document.getElementsByTagName("tr")
// let a = 1
for (let elem in info) {
if (info.id != "info") continue
else info.splice(info.indexOf(elem), 1)
}
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function onClick(a = 1) {
if (a % 2 == 0) {
info[i].style.visibility = "hidden"
buttons[i].innerText = "View More" // wrong
} else {
info[i].style.visibility = "visible"
buttons[i].innerText = "View Less" // wrong
}
a++
})
}
}
<button>Show Contents</button>
<table>
<tr id="info" style="visibility:hidden;">
<td width="80%">
<p style="width:80%;text-align:center; margin-left:1%">
The Planetarium is located on the first floor of the Science Centre. The planetarium has a shape of a sphere, 16.30 meters in diameter, the dome could also be used for extreme-wide-projections and other enhanced multi-media shows. It has a seating capacity
of 140 the digital theatre of Planetarium facilitates the observation of planets, moon, stars, nebula, displayed on full dome through an advance technology and thus Astronomy Secrets will be shared with the students and general public. High resolution
projectors operated through Digester 3 technology with digital audio system will provide a dazzling shows and that would be unforgettable experience. The shows will be in 3 languages Gujarati, Hindi and English.
</p>
</td>
</table>
错误:
未捕获的类型错误:无法设置未定义的属性(设置“innerText”) 在 HTMLButtonElement.onClick
【问题讨论】:
-
问题是关于
closure inside loops,就像之前评论的那样。此外,在第一个循环中,您使用了错误的变量info.id != "info"应该是info[elem].id != "info"。假设tr和button的索引相同不是一个好主意,因为如果您在页面上添加按钮或其他表格,索引可能会改变! -
问题是它只是整理出那些不同的tr,剩余的tr计数等于按钮计数@ManuelRomeiro
-
另一个问题是您的变量
a永远不会是 1 或任何其他数字,因为点击处理程序的第一个参数始终是event。
标签: javascript html button