如何根据父容器内子元素的display值及属性控制元素显示状态?
Solution to Hide "Show More" Based on Visible Season's Episode Count
Got it, let's tackle this problem step by step. Here's how you can implement this functionality using either vanilla JavaScript or jQuery, depending on what your project uses:
Vanilla JavaScript Implementation
This approach uses plain JavaScript without any libraries, making it lightweight and compatible with all modern browsers:
// Get the parent container holding all season items const seasonContainer = document.querySelector('.series-seasons-list-wrap'); // Find the active season item (the one with inline display: block) const activeSeasonItem = seasonContainer.querySelector('.js-season-list-item[style*="display: block"]'); // Handle cases where no active season is found (fallback to 0 episodes to avoid errors) const episodeCount = activeSeasonItem ? parseInt(activeSeasonItem.dataset.episodeCount, 10) : 0; // Get the "show-more" element we need to toggle const showMoreElement = document.querySelector('.show-more'); // Adjust visibility based on the episode count if (episodeCount < 6) { showMoreElement.style.display = 'none'; } else { // Optional: Restore default visibility if episode count is 6 or higher showMoreElement.style.display = ''; }
Key Details:
- The attribute selector
[style*="display: block"]specifically targets the season item with inline display set to block. - Using
parseInt(..., 10)ensures we convert thedata-episode-countvalue to a base-10 number, avoiding weird behavior with leading zeros. - The fallback to
0prevents errors if no active season is found (like if all items are hidden initially). - The optional
elseclause resets the "show-more" element's display if the episode count meets or exceeds 6—handy if users can switch between seasons dynamically.
jQuery Implementation
If your project already uses jQuery, here's a more concise version:
// Grab the episode count from the active season item (fallback to 0 if none found) const episodeCount = parseInt($('.series-seasons-list-wrap .js-season-list-item[style*="display:block"]').data('episode-count'), 10) || 0; // Toggle visibility: show if count >=6, hide if <6 $('.show-more').toggle(episodeCount >= 6);
Key Details:
- jQuery's
.data()method automatically pulls thedata-episode-countvalue, and we still useparseIntto ensure it's treated as a number. - The
.toggle()method simplifies visibility control—it handles both showing and hiding in one line based on the condition.
Edge Cases to Keep in Mind
- If multiple season items have
display:block(unlikely, but possible), the code will target the first one. If you need to handle multiple active items, switch toquerySelectorAll(vanilla) or.each()(jQuery) to loop through them. - Make sure all season items have the
data-episode-countattribute, otherwise the fallback value of0will trigger hiding the "show-more" element.
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

