You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中无需为所有标签定义变量实现心形图标的far/fas类名切换

Fixing Your Heart Toggle Function

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 classList as a string won't work (it's an object, not a plain string).
  • You're assigning to classList.toggle instead 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:

  • this in the onclick attribute 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 both fas and far perfectly switches the state:
    • If the element has fas, toggling removes it and adds far.
    • If the element has far, toggling removes it and adds fas.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:37:35