如何在頁面上篩選內容卡?
我創建了一篇包含三個類別的部落格文章:(數位行銷類別、提示和建議類別、加密貨幣類別)
我想做的是過濾它。
例如,如果我想查看數位行銷類別的所有文章,我將點擊此按鈕來顯示所有數位行銷類別並隱藏其他類別。
這是我的程式碼範例。問題是我的過濾器不起作用。問題出在哪裡?
我嘗試添加 JavaScript 使其工作,但仍然不起作用。問題出在哪裡?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | document.addEventListener( "DOMContentLoaded" , () => {
"use strict" ;
const filterButtons = document.querySelectorAll( '.blog-filters button' );
const articleCards = document.querySelectorAll( '.article-card' );
filterButtons.forEach(button => {
button.addEventListener( 'click' , () => {
const selectedCategory = button.getAttribute( 'data-category' );
articleCards.forEach(card => {
const cardCategory = card.getAttribute( 'data-category' );
if (selectedCategory === 'all' || selectedCategory === cardCategory) {
card.style.display = 'block' ;
} else {
card.style.display = 'none' ;
}
});
});
});
});
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | < section id = "blog" class = "blog" >
< div class = "row" >
< div class = "col-md-8" >
< div class = "posts-list" >
< div class = "row" >
< div class = "col-lg-6 col-md-6 d-md-flex article-card" data-category = "digital-marketing-category" >
Blog Card
</ div >
< div class = "col-lg-6 col-md-6 d-md-flex article-card" data-category = "tips-and-advice-category" >
Blog Card
</ div >
< div class = "col-lg-6 col-md-6 d-md-flex article-card" data-category = "cryptocurrency-category" >
Blog Card
</ div >
</ div >
</ div >
</ div >
< div class = "col-md-4" >
< div class = "sidebar" >
< h3 class = "sidebar-title" >Article Categories</ h3 >
< div class = "blog-filters" >
< button data-category = "filter-all" >All</ button >
< button data-category = "digital-marketing-category" >Digital Marketing</ button >
< button data-category = "tips-and-advice-category" >Tips & Advice</ button >
< button data-category = "cryptocurrency-category" >Cryptocurrency</ button >
</ div >
</ div >
</ div >
</ div >
</ section >
|