如何在 vanilla JS DOM 操作中获取 DRY 代码

How to get DRY code in vanilla JS DOM manipulation

我正在开发一个天气应用程序,但在让我的代码变干时遇到了一些问题。当我使用很多 DOM 方法时会发生这种情况。这是一些代码:

if(document.querySelector('.container').contains(document.querySelector('.results__container')) 
    && document.querySelector('.container').contains(document.querySelector('.results__weather--temperature'))
    && document.querySelector('.container').contains(document.querySelector('.city__name')))
{
    document.querySelector('.container').removeChild(document.querySelector('.results__container'));
    document.querySelector('.container').removeChild(document.querySelector('.results__weather--temperature'));
    document.querySelector('.container').removeChild(document.querySelector('.city__name'));
}

还有一些:

if(weather.main === 'Haze' || weather.main === 'Mist' || weather.main === 'Smoke')
{
    //remove css of previous city's weather
    document.querySelector('.container').className = 'container';
    document.querySelector('.mist__container--outer').classList.remove('appear');
    document.querySelector('.cloud__container').classList.remove('appear');/
    document.querySelector('.sun').classList.remove('appear');

    //add css of new city's weather
    document.querySelector('.container').classList.add('background__mist');
    document.querySelector('.mist__container--outer').classList.add('appear');
}

检索您在多个地方使用的 DOM 元素,并将它们存储在变量中以备日后参考:

let c = document.querySelector('.container')
let rc = document.querySelector('.results__container')
let wt = document.querySelector('.results__weather--temperature')
let cn = document.querySelector('.city__name')

if(c.contains(rc) 
    && c.contains(wt)
    && c.contains(cn))
{
    c.removeChild(rc);
    c.removeChild(wt);
    c.removeChild(cn);
}

在你的第二个例子中同样如此(并且还缩短了初始 if()):

if(['Haze', 'Mist', 'Smoke'].includes(weather.main))
{
    let mco = document.querySelector('.mist__container--outer');
    //remove css of previous city's weather
    let c = document.querySelector('.container');

    c.className = 'container';
    mco.classList.remove('appear');
    document.querySelector('.cloud__container').classList.remove('appear');
    document.querySelector('.sun').classList.remove('appear');

    //add css of new city's weather
    c.classList.add('background__mist');
    mco.classList.add('appear');
}