我试图根据内容更改卡片的背景颜色,但它跳过了第一张卡片/div。设置背景颜色时,如何防止跳过第一张卡?Blazor Fiddle
@foreach (TimeLog time in timeList)
{
<div class="largeCard" id="cardstyle" style="background-color: @cardColour ">
<div>
@if (time.LogType == "Work") cardColour = "#06065c";
else cardColour = "#5c0606";
<h6>@time.LogType</h6>
</div>
</div>
}
@code {
List<TimeLog> timeList = new List<TimeLog>();
TimeLog times = new TimeLog();
string cardColour;
public class TimeLog
{
public string LogType { get; set; }
}
protected override async Task OnInitializedAsync()
{
times = new TimeLog();
times.LogType = "Work";
timeList.Add(times);
times = new TimeLog();
times.LogType = "Vacation";
timeList.Add(times);
times = new TimeLog();
times.LogType = "Work";
timeList.Add(times);
times = new TimeLog();
times.LogType = "Work";
timeList.Add(times);
times = new TimeLog();
times.LogType = "Vacation";
timeList.Add(times);
times = new TimeLog();
times.LogType = "Work";
timeList.Add(times);
}
}
您需要用if语句包围您的div元素,或者只需将if语句放在div之前。它会跳过它,因为在使用cardColour变量之后会评估您的if。所以,它应该是把你所有卡片的颜色都去掉1。
@if (time.LogType == "Work") cardColour = "#06065c";
else cardColour = "#5c0606";
<div class="largeCard" id="cardstyle" style="background-color: @cardColour ">
<div>
<h6>@time.LogType</h6>
</div>
</div>