为什么当我搜索其他内容时,会删除以前的内容

  • 本文关键字:删除 搜索 其他 javascript api
  • 更新时间 :
  • 英文 :


为什么在搜索其他内容时会删除以前的内容?例如,首先搜索鸡蛋并显示内容,但当搜索牛肉时,程序会删除鸡蛋并只显示牛肉。代码:

const searchBtn = document.getElementById('search-btn');
const mealList = document.getElementById('meal');
const mealDetailsContent = document.querySelector('.meal-details-content');
const recipeCloseBtn = document.getElementById('recipe-close-btn');
// event listeners
searchBtn.addEventListener('click', getMealList);
mealList.addEventListener('click', getMealRecipe);
recipeCloseBtn.addEventListener('click', () => {
mealDetailsContent.parentElement.classList.remove('showRecipe');
});

// get meal list that matches with the ingredients
function getMealList(){
let searchInputTxt = document.getElementById('search-input').value.trim();
fetch(`https://www.themealdb.com/api/json/v1/1/filter.php?i=${searchInputTxt}`)
.then(response => response.json())
.then(data => {
let html = "";
if(data.meals){
data.meals.forEach(meal => {
html += `
<div class = "meal-item" data-id = "${meal.idMeal}">
<div class = "meal-img">
<img src = "${meal.strMealThumb}" alt = "food">
</div>
<div class = "meal-name">
<h3>${meal.strMeal}</h3>
<a href = "#" class = "recipe-btn">Get Recipe</a>
</div>
</div>
`;
});
mealList.classList.remove('notFound');
} else{
html = "Sorry, we didn't find any meal!";
mealList.classList.add('notFound');
}
mealList.innerHTML = html;
});
}

这是因为每次都要替换mealList元素中的内容。

一个简单的解决方法是在更新innerHTML值之前检索它

类似的东西

let html = mealList.innerHTML;

与其每次调用函数都以空开始,不如使用该函数。