如何在JavaScript中无需为所有标签定义变量实现心形图标的far/fas类名切换
Hey there! Let's get this sorted out. The main issues with your current code are:
- You're using multiple functions (
like,like1) which isn't scalable for many elements. - Checking
classListas a string won't work (it's an object, not a plain string). - You're assigning to
classList.toggleinstead of calling it as a method (it needs parentheses!).
Here's a simple, scalable solution that uses one function for all heart icons:
Step 1: Update Your HTML
Change both onclick handlers to pass this (which refers directly to the clicked <i> element) to a single function:
<div class="cont"> <h2>A header</h2> <div class="heart"> <i onclick="toggleHeart(this)" class="fas fa-heart"></i> </div> </div> <div class="cont"> <h2>A header#2</h2> <div class="heart"> <i onclick="toggleHeart(this)" class="fas fa-heart"></i> </div> </div>
Step 2: Single JavaScript Function
This function handles all toggle cases cleanly by switching between the fas and far classes:
function toggleHeart(el) { // Toggle both classes to switch states el.classList.toggle('fas'); el.classList.toggle('far'); }
How It Works:
thisin theonclickattribute passes the exact<i>element that was clicked to the function.classList.toggle()adds a class if it's missing, or removes it if it's present. Toggling bothfasandfarperfectly switches the state:- If the element has
fas, toggling removes it and addsfar. - If the element has
far, toggling removes it and addsfas.
- If the element has
Bonus: Better Practice (No Inline Onclick)
As you keep learning, it's cleaner to separate your HTML and JavaScript. You can remove inline onclick attributes entirely and use event listeners instead:
// Wait for the page to fully load document.addEventListener('DOMContentLoaded', function() { // Get all heart icons on the page const heartIcons = document.querySelectorAll('.heart i'); // Add a click listener to each icon heartIcons.forEach(icon => { icon.addEventListener('click', function() { this.classList.toggle('fas'); this.classList.toggle('far'); }); }); });
This keeps your markup tidy and makes your code easier to maintain as you add more heart elements.
Hope this helps you understand how to handle multiple elements with a single function! 😊
内容的提问来源于stack exchange,提问作者Leena

