简体   繁体   English

从变量后面的代码更改css类-避免的方法?

[英]changing css class from code behind variable - way to avoid?

I need to change the background of a div based on some count property set in the code behind. 我需要根据后面的代码中设置的一些count属性来更改div的背景。 I can get it to work as below. 我可以使它按以下方式工作。 But i'm wondering if this is a good practice. 但是我想知道这是否是一个好习惯。 If I need to change the count logic, I have to update code vs html. 如果需要更改计数逻辑,则必须更新代码与html。 I suppose Jquery can't do this unless I have a hidden variable with count on the page. 我想除非我在页面上有一个带有count的隐藏变量,否则Jquery无法做到这一点。 Is this better than writing an If loop logic within the html? 这比在html中编写If循环逻辑好吗?

html html

<div class="show <%=CSSClass %>">  value </div>

code behind 背后的代码

public string CSSClass
            {
                get
                {
                    if (count > 1) return "bright";

                    else if (count == 0)
                        return "normal";

                    return "dim";
                }
            }

That's a good practice. 这是一个好习惯。 I would stick with it. 我会坚持下去。 If you wanted to do it with jQuery you could expose the count server side property to the client and perform the same logic on the client. 如果要使用jQuery,可以将count服务器端属性公开给客户端,并在客户端上执行相同的逻辑。 Note however that because this is done on the client there might be some delay after the page has rendered and the jQuery code has assigned the proper classname, so you could observe a flickering when the actual CSS class is applied to the DOM element on the client side. 但是请注意,由于此操作是在客户端上完成的,因此在页面呈现和jQuery代码分配了正确的类名之后可能会有一些延迟,因此当将实际CSS类应用于客户端上的DOM元素时,您可能会观察到闪烁侧。

类名是执行此操作的一种完全有效的方法,您在服务器上执行此操作的技巧也是如此。

If your trying to use the MVC methodology there is no need for this. 如果您尝试使用MVC方法,则无需这样做。

the point in MVC is to make sure that you have no buisness logic in your view, and since this not logic of that type it seems to complicated, I would put the if in the page. MVC中的要点是确保您的视图中没有商务逻辑,并且由于这种逻辑不是很复杂,因此我将if放在页面中。

Unless of course you are gonna use this alot and then this would be perhaps not a bad idea. 除非您当然要大量使用此功能,否则这可能不是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM