簡體   English   中英

如何檢索textContent並在復選框輸入中顯示

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

我正在嘗試構建一個小程序,您可以使用輸入字段將數據輸入其中,以構建一組包含列表項的無序列表。

我有一個復選框,當選中它時,我希望它顯示包含該文本位(在本例中為atlanta)的整個無序列表。 我希望將不包含此文本的其余無序列表設置為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鏈接。

任何幫助,不勝感激。

我聲明的幾個變量在這段代碼中是不必要的。 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為這個問題的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM