首页 > 解决方案 > 如何检索文本内容并在复选框输入上显示

问题描述

我正在尝试构建一个小程序,您可以使用输入字段输入数据来构建一组包含列表项的无序列表。

我有一个复选框,当它被选中时,我希望它显示包含该文本位的整个无序列表,在本例中为亚特兰大。我希望将其余不包含此文本的无序列表设置为display: none;

for 循环是问题所在,尽管我已经玩了一整天并且无法按照我的意愿行事。

这是我认为有问题的代码:

checkboxInput.addEventListener('change', (e) => {
  const isChecked = e.target.checked;
  let ulList = document.getElementsByTagName('ul');
  let liList = document.getElementsByTagName('li');
  let locationList = document.getElementsByClassName('location');

   if (isChecked) {
    for (let i = 0; i < ulList.length; i += 1) {
      for (let j = 0; j < liList.length; j += 1) {
        let ul = ulList[i];
      let li = liList[i]; 
        if (li.textContent == 'atlanta') {
        ul.style.display = '';
      } else {
        ul.style.display = 'none';
      }
      } 
    }
   }  
});

在此处查看 jsFiddle 链接。

非常感谢任何帮助。

标签: javascriptcheckboxaddeventlistener

解决方案


我声明的几个变量在这段代码中是不必要的。liList变量被替换为ulList.children。第二个 for 循环也不是必需的。这是为实现我需要的功能而更改的 eventListener。

checkboxInput.addEventListener('change', (e) => {
    const isChecked = e.target.checked;

    let ulList = document.getElementsByTagName('ul');
    if (isChecked) {
        for (let i = 0; i < ulList.length; i += 1) {
            let ul = ulList[i];
            let liList = ul.children;
            let li = liList[1];

            if (li.textContent == 'atlanta') {
                 ul.style.display = 'block';
            } else {
                 ul.style.display = 'none';
            }

        }
    } 
});

感谢Treehouse 的Kris对这个问题的解答。


推荐阅读