gpt4 book ai didi

javascript - 将类添加到数组中的项目并删除其他项目

转载 作者:行者123 更新时间:2023-12-01 02:10:24 25 4
gpt4 key购买 nike

我试图实现一些非常简单的事情。我有一份元素 list 。如果我点击一个,它应该给它一个选定的类。但是,如果我单击列表中的另一个项目。它应该从前一个元素中删除选定的类。这是我的 JavaScript 代码。

const timeRangeWrapper = document.querySelector('.time-range');
const timeOptions = timeRangeWrapper.querySelectorAll('.times .time-option');
timeOptions.forEach((item, i) => {
const domIndex = item.getAttribute('data-item');
item.addEventListener('click', () => {
if (i == domIndex) {
item.classList.add('selected');
} else if (i !== domIndex && item.classList.contains('selected')){
item.classList.remove('selected');
}
});
});

这是我的标记

<div class="time-range">
<span class="helper">Please select an exact booking time</span>
<ul class="times">
<li class="time-option" data-item="0">7.00PM</li>
<li class="time-option" data-item="1">7.15PM</li>
<li class="time-option" data-item="2">7.30PM</li>
<li class="time-option" data-item="3">7.45PM</li>
<li class="time-option" data-item="4">8.00PM</li>
</ul>
<div class="btn-wrapper form text-center mt-15">
<button data-accept="true" data-time-exact="false" class="btn booking btn-custom-primary text-small bold text-uppercase">Confirm</button>
</div>

最佳答案

您可以首先从所有选项中删除.active类,然后将类添加到单击的特定选项:

const timeRangeWrapper = document.querySelector('.time-range');
const timeOptions = timeRangeWrapper.querySelectorAll('.times .time-option');
timeOptions.forEach((item, i) => {
const domIndex = item.getAttribute('data-item');
item.addEventListener('click', () => {
timeOptions.forEach(option => {
option.classList.remove('selected');
})
if (i == domIndex) {
item.classList.add('selected');
}
});
});
.selected {
border: 1px solid red;
}
<div class="time-range">
<span class="helper">Please select an exact booking time</span>
<ul class="times">
<li class="time-option" data-item="0">7.00PM</li>
<li class="time-option" data-item="1">7.15PM</li>
<li class="time-option" data-item="2">7.30PM</li>
<li class="time-option" data-item="3">7.45PM</li>
<li class="time-option" data-item="4">8.00PM</li>
</ul>
<div class="btn-wrapper form text-center mt-15">
<button data-accept="true" data-time-exact="false" class="btn booking btn-custom-primary text-small bold text-uppercase">Confirm</button>
</div>
</div>

关于javascript - 将类添加到数组中的项目并删除其他项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793860/

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