簡體   English   中英

如何/何時刪除子元素以清除搜索結果?

[英]How/When to remove child elements to clear search result?

在我提交新的 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);
        }
    }
};

謝謝

而不是gallery.remove(galleryItems); 考慮在submit事件發生時將gallery.innerHTML重置為空字符串

像這樣:

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

我相信這會做到的..你很接近。

const galleryItems = document.getElementsByClassName('flexbox-item');

// to remove
galleryItems.forEach(elem => elem.remove() );

暫無
暫無

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

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