【问题标题】:How to delete the api displayed images while I'm trying to search for the new one?如何在我尝试搜索新图像时删除 api 显示的图像?
【发布时间】:2022-11-23 09:01:24
【问题描述】:
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TV Show Search</title>

    <script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
</head>
<body>
    <h1>TV Show Search</h1>
    <form id="searchForm">
        <input type="text" placeholder="TV Show title" name="query">
        <button>Search</button>

    </form>
    
    <script src="app.js"></script>
</body>
</html>

The result of displayed image in the browser

下面的代码是在 api 中搜索图片元素数据,它会在搜索后显示图片,我的目标是在显示第一个搜索到的图片时,当我尝试搜索不同的元素时,应该删除之前显示的图片。现在,当我搜索时,它会从浏览器中显示的最后一张图片的位置打印出来。

const form = document.querySelector('#searchForm');
const input = document.querySelector('.name');

form.addEventListener('submit', async function(e) {
    e.preventDefault();
    const searchTerm = form.elements.query.value;
    const config = {params: {q: searchTerm}}
    const res = await axios.get(`https://api.tvmaze.com/search/shows`, config)
    form.elements.query.value = ''
    // console.log(res.data[0].show.image.medium);
    // form.elements.query.value = '';
    // const img = document.createElement('IMG');
    // img.src = res.data[0].show.image.medium;
    // document.body.append(img)
    makeImages(res.data)
})

const makeImages = (shows) => {
    for(let result of shows){
        if(result.show.image) {
            const img = document.createElement('IMG');
            img.src = result.show.image.medium;
            document.body.append(img);
        }
    }
}

【问题讨论】:

    标签: javascript function api axios


    【解决方案1】:

    您应该为图像生成容器,然后在 makeImages 中应该做的第一件事就是清除容器内的所有子对象。

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 2021-12-25
      • 2017-03-15
      • 2021-11-03
      • 2020-07-09
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多