【问题标题】:How/When to remove child elements to clear search result?如何/何时删除子元素以清除搜索结果?
【发布时间】:2021-05-03 21:12:24
【问题描述】:

在我提交新的 API 调用后尝试清除我的搜索结果。尝试在不同点实现gallery.remove(galleryItems);,但无济于事。

有点失望,我无法弄清楚,但很高兴我能够让一些异步函数运行。无论如何,这是代码:

'use strict';

const form = document.querySelector('#searchForm');
const gallery = document.querySelector('.flexbox-container');
const galleryItems = document.getElementsByClassName('flexbox-item');

form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const userSearch = form.elements.query.value;   // grab user input
    const res = await getRequest(userSearch); // async func that returns a fully parsed Promise
    tvShowMatches(res.data); // looks for matches, creates and appends name + image;
    form.elements.query.value = '';
});

const getRequest = async (search) => {
    const config = { params: { q: search } };
    const res = await axios.get('http://api.tvmaze.com/search/shows', config);
    return res;
};

const tvShowMatches = async (shows) => {
    for (let result of shows) {
        if (result.show.image) {
            // new div w/ flexbox-item class + append to gallery
            const tvShowMatch = document.createElement('DIV')
            tvShowMatch.classList.add('flexbox-item');
            gallery.append(tvShowMatch);

            // create, fill & append tvShowName to tvShowMatch
            const tvShowName = document.createElement('P');
            tvShowName.textContent = result.show.name;
            tvShowMatch.append(tvShowName);

            // create, fill & append tvShowImg to tvShowMatch
            const tvShowImg = document.createElement('IMG');
            tvShowImg.src = result.show.image.medium;
            tvShowMatch.append(tvShowImg);
        }
    }
};

谢谢

【问题讨论】:

    标签: javascript function asynchronous promise


    【解决方案1】:

    只要发生submit 事件,请考虑将gallery.innerHTML 重置为空字符串,而不是gallery.remove(galleryItems);

    像这样:

    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      gallery.innerHTML = ''; // Reset here
      const userSearch = form.elements.query.value;   // grab user input
      const res = await getRequest(userSearch); // async func that returns a fully parsed Promise
      tvShowMatches(res.data); // looks for matches, creates and appends name + image;
      form.elements.query.value = '';
    });
    

    【讨论】:

    • 谢谢。当你指出它时,如此明显。不知道为什么我没想到。
    • 不客气。我很高兴它有帮助。你介意给它一个赞成票吗? @Vayl
    【解决方案2】:

    我相信这会做到的..你很接近。

    const galleryItems = document.getElementsByClassName('flexbox-item');
    
    // to remove
    galleryItems.forEach(elem => elem.remove() );
    

    【讨论】:

    • 试过了,恐怕对我没用。
    猜你喜欢
    • 2020-07-24
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多