【发布时间】:2020-09-17 18:32:19
【问题描述】:
我在 10 个月前编写了一个基于 ajax 的“JS TABS”,其中包含 .JSON 文件,现在想重用它,但不知道为什么它不起作用。从那以后我就没有碰过它,也不知道错误在哪里。
当我单击按钮渲染产品时,什么都不会打印出来 - 除了控制台告诉我:items is undefined = 所以我把它移到了function changeCategoryItems(categoryId) { } 里面,没有错误,但没有任何渲染......有人可以帮我吗?
这是我的意思的代码笔参考:https://codepen.io/Contemplator191/pen/WNwgypY 这是 JSON:https://api.jsonbin.io/b/5f634e0c302a837e95680846
如果 codepen 不适合/不允许,这里是整个 JS
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
buttons.forEach(function (button) {
button.addEventListener('click',event => {
changeCategoryItems(event.target.dataset.category);
});
});
function changeCategoryItems(categoryId) {
let items = [];
const buttons = document.querySelectorAll('button');
const wrapper = document.querySelector('section.products');
const viewItems = (categoryId == 0 ) ? items : items.filter(item => item.category == categoryId);
wrapper.innerHTML = "";
viewItems.forEach(item => {
const div = document.createElement('div');
div.setAttribute("class", "product");
div.innerHTML = createItem(item);
wrapper.appendChild(div);
});
};
function createItem(item) {
return `
<div class="product__img">
<img src="${item.img}" class="">
</div>
<div class="product__name _tc">
<h4 class="">${item.heading}</h4>
</div>
<div class="text-desc product__desc">
<p class="">${item.description}</p>
</div>
<div class="product__bottom-content">
<span class="product__info">${item.info}</span>
<a href="" role="button" class="btn btn--teal btn--animated product__btn">${item.btn}</a>
</div>
`
}
fetch('https://api.jsonbin.io/b/5f634e0c302a837e95680846')
.then(function (res) { return res.json() })
.then(function (data) {
items = data.items;
changeCategoryItems(1);
});`
【问题讨论】:
标签: javascript json tabs