JavaScript单选按钮切换文章分类功能实现求助
Hey there! Let's get this working properly. First, I spotted a critical issue in your existing HTML: your radio buttons have mismatched name attributes (two use name="France"), which breaks the single-select behavior of radio buttons. Let's fix that first, then build the JavaScript logic to filter and display your news content.
Step 1: Fix the Radio Button Group HTML
All radio buttons in a single-select group need the same name attribute. Let's update that to something like newsCategory, and add a value attribute matching the category name (this makes the JavaScript filtering cleaner):
<div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="newsCategory" id="france" value="France" checked> France </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="monde" value="Monde"> Monde </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="culture" value="Culture"> Culture </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="sports" value="Sports"> Sports </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="economie" value="Economie"> Economie </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="regions" value="Régions"> Régions </label> <label class="btn btn-primary"> <input type="radio" name="newsCategory" id="divers" value="Divers"> Divers </label> </div> <!-- Add a container to display filtered news content --> <div id="newsContent" class="mt-3"></div>
Step 2: Define Your News Array Structure
I’ll assume your $afamilyNews array has objects with a category property (matching the radio button values) and a content property (the news text to display). Adjust this to match your actual data structure:
// Your news array (customize to fit your real data) const $afamilyNews = [ { category: "France", content: "🚨 Latest updates from Paris: New transport reforms announced." }, { category: "France", content: "🎉 French national holiday celebrations draw record crowds." }, { category: "Monde", content: "🌍 Global climate summit reaches landmark agreement." }, { category: "Culture", content: "🎨 New impressionist exhibition opens in Marseille." }, { category: "Sports", content: "⚽ French football team qualifies for international tournament." }, { category: "Economie", content: "💶 Eurozone inflation rates drop to 2-year low." }, { category: "Régions", content: "🌾 Agricultural innovations boost crop yields in Brittany." }, { category: "Divers", content: "🐶 Paris launches new pet-friendly park initiative." } ];
Step 3: JavaScript Logic to Filter and Display Content
We’ll add event listeners to the radio buttons, filter the array when a selection changes, and render the results in the newsContent container. We’ll also handle the initial page load to show the default selected category (France):
// Get references to key elements const radioButtons = document.querySelectorAll('input[name="newsCategory"]'); const newsContentContainer = document.getElementById('newsContent'); // Function to render filtered news items function renderNews(selectedCategory) { // Filter the array to get only items matching the selected category const filteredNews = $afamilyNews.filter(item => item.category === selectedCategory); // Clear previous content newsContentContainer.innerHTML = ''; // Handle empty category case if (filteredNews.length === 0) { newsContentContainer.innerHTML = '<p>No news available for this category.</p>'; return; } // Create HTML for each news item (customize styling to match your site) filteredNews.forEach(newsItem => { const newsCard = document.createElement('div'); newsCard.className = 'card mb-2 p-3'; newsCard.textContent = newsItem.content; newsContentContainer.appendChild(newsCard); }); } // Add change event listeners to all radio buttons radioButtons.forEach(radio => { radio.addEventListener('change', () => { if (radio.checked) { renderNews(radio.value); } }); }); // Initial render: show content for the default selected category renderNews(document.querySelector('input[name="newsCategory"]:checked').value);
Key Notes
- Radio Button Consistency: The
nameattribute must be identical for all radio buttons in the group to ensure only one can be selected at a time. Thevalueattribute aligns directly with your category names for easy filtering. - Array Filtering: The
filter()method grabs only the news items matching the selected category. If your array uses a different property name (e.g.,catinstead ofcategory), adjust the filter logic accordingly. - Rendering Flexibility: The example uses Bootstrap-style cards, but you can modify the HTML template to match your site’s existing styling (e.g., plain paragraphs, custom divs).
内容的提问来源于stack exchange,提问作者Kimako

