我编写了一些普通的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相关问答推荐

在shiny 模块中实现JavaScript

如何在非独立组件中使用独立组件?

Angular:ng-contract未显示

为什么JavaScript双边字符串文字插值不是二次的?

如何通过onClick为一组按钮分配功能;

yarn安装一个本地npm包,以便本地包使用main项目的node_modules(ckeditor-duplicated-modules错误)

如何修复我的js构建表每当我添加一个额外的列作为它的第一列?

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

如何将react—flanet map添加到remixjs应用程序

在使用HighChats时如何避免Datatables重新初始化错误?

我可以使用空手道用户界面来获取网页的当前滚动位置吗?

如何将未排序的元素追加到数组的末尾?

为什么JPG图像不能在VITE中导入以进行react ?

按下单键和多值

在Odoo中如何以编程方式在POS中添加产品

如何在FiRestore中的事务中使用getCountFromServer

谷歌饼图3D切片

rxjs在每次迭代后更新数组的可观察值

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?