【问题标题】:Colour the background of a card based on the card content - why is it skipping the first card?根据卡片内容为卡片的背景着色 - 为什么会跳过第一张卡片?
【发布时间】:2020-03-31 18:56:54
【问题描述】:

我正在尝试根据内容更改卡片的背景颜色,但它跳过了第一张卡片/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);
    }
}

【问题讨论】:

    标签: c# html css blazor blazor-server-side


    【解决方案1】:

    您需要用 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>
    

    【讨论】:

    • 成功!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2021-08-12
    • 2021-02-19
    • 2021-07-07
    • 2021-07-21
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多