咨询:文章列表中用于JS筛选的文章标签应选用哪种HTML属性
Great question! For your scenario of adding tags (like patchnotes, news, all) to articles in a list for JavaScript-powered filtering, using a data-* attribute is the perfect choice—it’s purpose-built for storing custom, script-accessible data in HTML.
Here’s my specific recommendation:
- Use
data-tagsas your attribute name. It’s descriptive, follows HTML5’sdata-*naming rules (lowercase, no special characters), and immediately communicates the attribute’s purpose to anyone reading your code. - For articles with multiple tags, separate the values with spaces, e.g.,
data-tags="patchnotes all". This makes it easy to split the value into an array in JavaScript when matching filter criteria.
Why not use class instead?
While you could use class names for filtering, the class attribute is intended primarily for styling. Mixing filter tags with style classes can lead to confusion down the line (e.g., accidentally overriding a style class when adding a new filter tag) and makes your code less semantically clear. data-* attributes avoid this confusion by being explicitly for script-related data.
Quick Example
<!-- Sample article items --> <article class="article-card" data-tags="patchnotes all"> <h2>Version 2.1 Patch Notes</h2> </article> <article class="article-card" data-tags="news all"> <h2>Community Event Announcement</h2> </article> <!-- Filter buttons --> <button class="filter-button" data-filter="patchnotes">Patch Notes</button> <button class="filter-button" data-filter="news">News</button> <button class="filter-button" data-filter="all">All Articles</button>
This approach is compliant with HTML standards, maintainable, and perfectly tailored to your filtering needs.
内容的提问来源于stack exchange,提问作者nook

