我正在嘗試在 javascript 中實作某些目標
我想為每個類別設定特定的顏色
例如:如果category.name == x 那么color = blue 如果category.name == y 那么color = red ...
我試過這樣,但我想我錯過了一些東西:
categories.forEach(category => {
if (category.attributes.slug = "animation") {
cat.style.color = animColor;
}
if (category.attributes.slug = "decor") {
cat.style.color = decorColor;
}
if (category.attributes.slug = "illustrations") {
cat.style.color = illuColor;
}
if (category.attributes.slug = "developpement-visuel") {
cat.style.color = devVisuel;
}
if (category.attributes.slug = "realisations") {
cat.style.color = real;
}
if (category.attributes.slug = "croquis") {
cat.style.color = croquis;
}
});
<div>
<Header
categories={categories}
homepage={homepage} />
<div className="hidden md:block px-5 pt-10">
<a className="hover:no-underline " href="/">
<h3 className="text-xl uppercase tracking-widest mb-4">{homepage.attributes.hero.title}</h3>
</a>
<h5 className="text-sm mb-10">{homepage.attributes.bio.text}</h5>
<nav>
<ul>
{categories.map((category) => {
return (
<li key={category.id} className="mb-4">
<Link href={`/category/${category.attributes.slug}`}>
<a id="cat" className="uppercase font-light text-sm">{category.attributes.name}</a>
</Link>
</li>
)
})}
</ul>
</nav>
</div>
</div>
你能幫我找到解決辦法嗎?
uj5u.com熱心網友回復:
您可以將物件用作將“slug”翻譯為“color”的字典。
您可以在 categories.map 內部函式中設定顏色屬性。
我洗掉了 id="cat" 因為這會導致重復的 ID 永遠不會好。
const colorMap = {
"animation": animColor,
"decor": decorColor,
"illustrations": illuColor,
"developpement-visuel": devVisuel,
"realisations": real,
"croquis": croquis
};
<div>
<Header
categories={categories}
homepage={homepage} />
<div className="hidden md:block px-5 pt-10">
<a className="hover:no-underline " href="/">
<h3 className="text-xl uppercase tracking-widest mb-4">{homepage.attributes.hero.title}</h3>
</a>
<h5 className="text-sm mb-10">{homepage.attributes.bio.text}</h5>
<nav>
<ul>
{categories.map((category) => {
return (
<li key={category.id} className="mb-4">
<Link href={`/category/${category.attributes.slug}`}>
<a className="uppercase font-light text-sm" style=`color: ${colorMap[category.attributes.slug]}`>{category.attributes.name}</a>
</Link>
</li>
)
})}
</ul>
</nav>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438484.html
標籤:javascript 循环 前锋
上一篇:打造“拋硬幣”游戲
下一篇:提高C中嵌套回圈的性能
