如何使用Blazor更改div元素的类 [英] How to change classes of a div element using Blazor

查看:650
本文介绍了如何使用Blazor更改div元素的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在cshtml页面中具有以下形式的典型div元素:

I have a typical div element in a cshtml page in the form:

<div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>

Pre Blazor,我通常会使用jQuery在div中添加或删除hide-errors类.但是,Blazor试图消除对JavaScript的需求,而我正在尝试使用尽可能少的JSInterop. Blazor中有什么方法可以做到这一点?

pre Blazor, I'd typically use jQuery to add or remove the hide-errors class from the div. However, Blazor is trying to remove the need for JavaScript and I'm trying to use as little JSInterop as possible. Is there a way in Blazor to do this?

所以在Blazor中我可以这样做:

so in Blazor I could do:

 @if (!string.IsNullOrEmpty(ErrorMessage))
 {
     <div id="loginErrors" class="alert alert-danger">@(ErrorMessage)</div>
 }
 else
 {
     <div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>
 }

或使用JSinterop:

or using JSinterop :

删除要求:

await JSRuntime.Current.InvokeAsync<object>("blazorExtensions.RemoveClass", "loginErrors", "hide-errors");

函数通常为:

RemoveClass: function (id, classname) {
    var tt = '#' + id;
    $(tt).removeClass(classname);
}

与用于添加类的类似.以上两项工作均已完成,但如上所述.我试图避免JSInterop路由,并且我不喜欢将div元素声明两次,即使只有一个会进入DOM.

with similar for adding a class. Both of the above work, but as mentioned. I'm trying to avoid the JSInterop route and I don't like the div element being declared twice even though only one will get into the DOM.

推荐答案

就像在普通剃刀中一样:

Just like you would in regular Razor:

@if (price>30)
{
    <p>The price is too high.</p>
}

编辑 对于更新的问题,我想您想要这样做:

EDIT For updated question, I guess you want this:

<div class="@((string.IsNullOrEmpty(ErrorMessage)? "hide-errors" : ""))">

这篇关于如何使用Blazor更改div元素的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆