我编写了一些普通的 JS 来隐藏/显示一些 div,具体取决于其中一个字段的值。
我的问题是,虽然默认情况下可以适当隐藏它们,但尝试使它们再次出现时,我遇到了问题,因为使用 getElementById 返回空值。
我在谷歌上搜索并发现了许多类似代码有效的示例,但我无法弄清楚为什么我的代码实际上不起作用。
我写的JS如下:
var hidden = false
document.addEventListener("keypress", function(event) {
if (event.key == '`') {
if (hidden == false) {
resultEntries = document.getElementsByClassName('result-row');
for (i = 0; i < resultEntries.length + 1; i++) {
var x = document.getElementById('root_cause_' + i)
if (x != null) {
var value = x.options[x.selectedIndex].value;
console.log('value' + value)
if (value == '') {
row = document.getElementById('line_' + i)
row.style.display = 'none';
}
}
}
hidden = true
} else {
resultEntries = document.getElementsByClassName('result-row');
for (i = 0; i < resultEntries.length + 1; i++) {
row = document.getElementById('line_' + i) // This is what is returning null
console.log(row)
row.style.display = 'block';
}
hidden = false
}
}
});
最佳答案
在 for 循环中使用 + 1
超出元素
如果您需要这个 1 基础(不推荐),那么它是
for (let i = 1; i <= resultEntries.length; i++)
我认为你可以简化这个。这是我在没有看到 HTML 的情况下的猜测
const resultEntries = document.querySelectorAll('.result-row');
document.addEventListener("keypress", function(event) {
if (event.key !== '`') return;
resultEntries.forEach((res, i) => {
let x = document.getElementById('root_cause_' + i)
if (x) {
let value = x.value;
console.log('value' + value)
document.getElementById('line_' + i).hidden = value === '';
}
})
});
关于javascript - 无法使用 Javascript 切换 div 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73704476/