如何用JavaScript根据season-list的data属性隐藏指定触发元素
Solution to Hide Show More Trigger for Seasons with Fewer Than 6 Episodes
Got it, let's get this sorted for you! Here's a straightforward way to adjust your existing script to hide the .js-show-more-trigger elements whenever their corresponding .season-list has a data-episode-count value less than 6:
Step-by-Step Script Implementation
// Grab all elements with the season-list class const seasonLists = document.querySelectorAll('.season-list'); // Iterate over each season list element seasonLists.forEach(seasonList => { // Retrieve the episode count from the data attribute, convert to a number const episodeCount = Number(seasonList.dataset.episodeCount); // Check if the episode count is less than 6 if (episodeCount < 6) { // Locate the associated js-show-more-trigger element // 📌 Adjust this selector based on your actual DOM structure: // Example 1: Trigger is a direct sibling of the season-list const trigger = seasonList.nextElementSibling?.closest('.js-show-more-trigger'); // Example 2: Trigger is inside the same parent container as season-list // const trigger = seasonList.parentElement.querySelector('.js-show-more-trigger'); // Hide the trigger if it exists (avoid null errors) if (trigger) { trigger.style.display = 'none'; // Optional: Use a CSS class instead for better maintainability // trigger.classList.add('hidden'); } } });
Key Notes to Keep in Mind
- Convert to Number: Always convert the
data-episode-countvalue to a number (usingNumber()orparseInt())—since data attributes return strings, direct string comparison (like"5" < "6") works here but is risky for larger numbers (e.g.,"10" < "6"would incorrectly returntrue). - Target the Correct Trigger: Make sure the logic to find the
.js-show-more-triggermatches your DOM structure. The examples above cover common scenarios, but you may need to tweak the selector if your elements are nested differently. - Avoid Null Errors: Using the optional chain operator (
?.) ensures that if no trigger is found, the script won't throw an error. - Optional CSS Class Tip: Instead of directly modifying the
displaystyle, define a CSS class like.hidden { display: none; }and usetrigger.classList.add('hidden'). This keeps your style logic in CSS where it belongs, making updates easier later.
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

