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

Svelte中如何动态修改类名?点击按钮无法更改指定Div背景问题求助

解决点击按钮后无法修改指定日期div背景色的问题

你的代码存在类型不匹配的问题,导致点击按钮后目标div的背景色未生效:

原始代码

<script>
let mydate = [new Date(2023, 9, 24).toDateString()];
const getClass = (date) => {
  return mydate.includes(date) ? "myclass": ""
}
</script>
<style>
.myclass { background-color: yellow; } 
</style>
<button on:click={() => {mydate = [...mydate, new Date(2023, 9, 25)]}}>click</button>
<div class={getClass(new Date(2023, 9, 24).toDateString())}>{new Date(2023, 9, 24)}</div>
<div class={getClass(new Date(2023, 9, 25).toDateString())}>{new Date(2023, 9, 25)}</div>

问题原因

mydate数组初始存储的是日期字符串(通过toDateString()转换),但点击按钮时向数组添加的是Date对象。includes()方法会严格匹配类型,字符串和Date对象永远无法匹配,因此getClass方法无法识别2023-10-25对应的日期字符串,也就不会给目标div添加myclass类。

修复方案

修改按钮的点击事件,将待添加的Date对象同样转换为toDateString()后的字符串,保证数组内元素类型统一:

<script>
let mydate = [new Date(2023, 9, 24).toDateString()];
const getClass = (date) => {
  return mydate.includes(date) ? "myclass": ""
}
</script>
<style>
.myclass { background-color: yellow; } 
</style>
<button on:click={() => {mydate = [...mydate, new Date(2023, 9, 25).toDateString()]}}>click</button>
<div class={getClass(new Date(2023, 9, 24).toDateString())}>{new Date(2023, 9, 24)}</div>
<div class={getClass(new Date(2023, 9, 25).toDateString())}>{new Date(2023, 9, 25)}</div>

修改后点击按钮,mydate数组会新增2023-10-25对应的日期字符串,getClass方法能成功匹配,目标div会被加上myclass类,背景变为黄色。

内容的提问来源于stack exchange,提问作者27 D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:50:14