gpt4 book ai didi

JavaScript 改变 HTML 元素的类

转载 作者:行者123 更新时间:2023-12-03 03:31:46 25 4
gpt4 key购买 nike

我想根据系统日期将 class="filter" 更改为 class="active filter"。我知道如何获得系统日,但无法更改类(class)。谁能帮我解决这个问题吗?

<li id="0"><a href="javascript:;" data-filter="all" class="active filter">All</a></li>
<li id="1"><a href="javascript:;" data-filter=".monday" class="filter"> Monday</a></li>
<li id="2"><a href="javascript:;" data-filter=".tuseday" class="fiter">Tuesday </a></li>
<li id="3"><a href="javascript:;" data-filter=".wednesday" class="filter"> Wednesday</a></li>
<li id="4"><a href="javascript:;" data-filter=".thursday" class="filter"> Thursday</a></li>

最佳答案

使用 JavaScript 更改类:

element.classList.add     // adds a class
element.classList.remove // removes a class

您将循环遍历元素,并将事件类添加到与您的系统日期匹配的类中。 (您可以使用 getAttribute('data-filter') 与您的系统日期进行比较。)

var sysDay = 'monday';

var activeDay = function(sysDay) {
var days = document.getElementsByClassName('day');
for (var i=0; i<days.length; i++) {
// remove active class
days[i].classList.remove('active');
// add active class only if matches system day
if ( (days[i].getAttribute("data-filter")) == sysDay )
{
days[i].classList.add('active');
}
}
}

activeDay(sysDay);
.active {
color: red;
}
<li id="0"><a href="javascript:;" data-filter="all" class="active filter day">All</a></li>
<li id="1"><a href="javascript:;" data-filter="monday" class="filter day"> Monday</a></li>
<li id="2"><a href="javascript:;" data-filter="tuseday" class="fiter day">Tuesday </a></li>
<li id="3"><a href="javascript:;" data-filter="wednesday" class="filter day"> Wednesday</a></li>
<li id="4"><a href="javascript:;" data-filter="thursday" class="filter day"> Thursday</a></li>

关于JavaScript 改变 HTML 元素的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46065593/

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