gpt4 book ai didi

javascript - 如何在单击事件中附加和删除 Font Awesome 图标 (Javascript)

转载 作者:行者123 更新时间:2023-12-04 00:50:37 25 4
gpt4 key购买 nike

我正在尝试编写 JavaScript 代码,如果那里还没有勾号,则在单击时将 FA 勾号图标应用到一天,如果有,则删除勾号。我已经编写了附加图标的代码,但不知道如何删除它

这是我的

HTML 和 JS:

const days = document.getElementsByClassName('day')
for (let i = 0; i < days.length; i++) {
days[i].addEventListener('click', function(e){
const tick = document.createElement('i');
tick.classList = 'fas fa-check-square fa-4x'
this.append(tick);
});
}
<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

最佳答案

您可以检查元素 i 是否已经存在,如果不存在则创建元素并将类添加到元素。如果存在,则删除该元素。

您可以尝试以下方式:

const days = document.getElementsByClassName('day')
for (let i = 0; i < days.length; i++) {
days[i].addEventListener('click', function(e){
if(!this.querySelectorAll('i').length){ // check if i is not exist
const tick = document.createElement('i');
this.append(tick);
tick.classList.add('fas', 'fa-check-square', 'fa-4x'); // add classes
}
else{
var elem = this.querySelector('i');
elem.parentNode.removeChild(elem); // remove i
}

})
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

关于javascript - 如何在单击事件中附加和删除 Font Awesome 图标 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66842031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com