简体   繁体   English

如何检索textContent并在复选框输入中显示

[英]How to retrieve textContent and display on checkbox input

I am trying to build a small program which you enter data into using input fields to build a set of unordered lists containing list items. 我正在尝试构建一个小程序,您可以使用输入字段将数据输入其中,以构建一组包含列表项的无序列表。

I have a checkbox of which that when it is checked, i would like it to display the entire unordered list that contains that bit of text, in this case, atlanta. 我有一个复选框,当选中它时,我希望它显示包含该文本位(在本例中为atlanta)的整个无序列表。 I would like the rest of the unordered lists which do not contain this text to be set to display: none; 我希望将不包含此文本的其余无序列表设置为display: none;

The for loop is the issue, though I have been playing around all day and cannot behave as I would like. for循环是个问题,尽管我整天都在玩,但无法表现出我想要的行为。

This is the code in question I believe: 我相信这是有问题的代码:

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';
      }
      } 
    }
   }  
});

Please see a jsFiddle link here . 在此处查看jsFiddle链接。

Any help much appreciated. 任何帮助,不胜感激。

A couple of the variables I declared were unnecessary in this piece of code. 我声明的几个变量在这段代码中是不必要的。 The liList variable was replaced with ulList.children . liList变量已替换为ulList.children The second for loop wasn't necessary either. 第二个for循环也没有必要。 Here is the eventListener changed to achieve the functionality I required. 这是更改的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';
            }

        }
    } 
});

Thanks to Kris from Treehouse for the answer to this problem. 感谢Treehouse的Kris为这个问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM