简体   繁体   English

如何优化我为制作手风琴而编写的代码?

[英]How can I optimize this code that I wrote to make an accordion?

dear friends, I am just learning javascript and I wrote a code to make an accordion, but I feel that there are much better ways to implement this accordion, I would be grateful if you could guide me with the methods Get to know better.亲爱的朋友们,我刚刚学习javascript,我写了一个代码来制作一个手风琴,但是我觉得有更好的方法来实现这个手风琴,如果你能指导我更好地了解这些方法,我将不胜感激。 This is the code I wrote:这是我写的代码:

const inputs = document.querySelectorAll('input');
const contents = document.querySelectorAll('.content')

let activeTarget;
for (let i = 0; i < contents.length; i++) {
    inputs[i].addEventListener("click",
        (event) => {
            if (contents[i].classList.value === "content open") {
                contents[i].classList.remove('open')
            }
            else if (activeTarget !== undefined) {
                activeTarget.classList.remove('open')
                contents[i].classList.add('open')
                activeTarget = contents[i]
            } else {
                contents[i].classList.add('open')
                activeTarget = contents[i];
            }
        }
        )
}

Rather than IF statements, you can just preemptively remove the 'open' class from all, then reapply it for the activeTarget.而不是 IF 语句,您可以抢先从所有中删除“打开”class,然后将其重新应用于 activeTarget。 I did add an IF statement to allow the user to close an accordion item by clicking on it again.我确实添加了一个 IF 语句,以允许用户通过再次单击来关闭手风琴项目。

const inputs = document.querySelectorAll('input');
const contents = document.querySelectorAll('.content')
let activeTarget;

contents.forEach(item => item.addEventListener("click", e => {
  contents.forEach(i => i.classList.remove('open'));
  if (activeTarget == e.target) {
     activeTarget = null;
     return;
  }
  activeTarget = e.target;
  activeTarget.classList.add('open');
}))

Reduce the else if and else into just one else , then check if activeTarget is undefined in the new else .else ifelse简化为一个else ,然后检查是否在新的elseundefined activeTarget This reduces duplicated code.这减少了重复的代码。

Then let's change the condition in the if to use contains instead.然后让我们更改if中的条件以使用contains代替。 This will be safer, because you don't check if the class list is exactly content open .这会更安全,因为您不检查 class 列表是否完全是content open Instead you only test if the element has the open class.相反,您只测试元素是否具有open的 class。

if (contents[i].classList.contains("open")) {
    contents[i].classList.remove('open')
} else {
    if (activeTarget !== undefined)
        activeTarget.classList.remove('open')
    contents[i].classList.add('open')
    activeTarget = contents[i]
}

My bet would be:我的赌注是:

// one click listener for the document rather than for every element
document.addEventListener((e) => {
  // if the user clicks on inputs
  if (e.currentTarget.tagName === 'input') {
    // input & accordion items are bound with the data-id attribute,
    // make sure elements have data-id attributes with the right values
    const current = document.querySelector(`.content[data-id="${e.currentTarget.dataset.id}"]`)
    // remove "open" class for every accordion item
    document.querySelectorAll('.content').forEach((item) => {
      item.classList.remove('open');
    });
    // toggle "open" class on the accordion item
    current.classList.toggle('open');
  }
});

Feel free to ask questions about the code in the comments.随时在评论中询问有关代码的问题。 Thanks.谢谢。

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

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