简体   繁体   English

以编程方式从HTML元素中删除特定的类名称

[英]Programmatically remove specific class name from HTML element

In C# ASP.NET I am adding a class to an <input> using: 在C#ASP.NET中,我使用以下命令向<input>添加一个类:

myInput.Attributes.Add("class","myClass");

At some point I would like to remove the added class (not all classes). 在某些时候,我想删除添加的类(不是所有类)。 Is there an equivalent along the lines of: 有没有相应的:

myInput.Attributes.Remove("class","myClass");

.Remove() seems to only accept a key (no pair value). .Remove()似乎只接受一个键(没有对值)。 Thank you! 谢谢!

There is nothing built in to manage multiple values in the attribute. 没有内置任何内容来管理属性中的多个值。

You will have to parse the list, remove the class name and update the attribute. 您必须解析列表,删除类名并更新属性。

Something like (untested): 像(未经测试)的东西:

var classes = myInput.Attributes["class"].Split(' ');

var updated = classes.Where(x => x != "classtoremove").ToArray();

myInput.Attributes["class"] = string.Join(" ", updated);

I got inspired by Odeds post and created these two extension methods for you to elaborate with; 我受到Odeds帖子的启发,并创建了这两种扩展方法供您详细说明;

public static void AddCssClass(this WebControl control, params string[] args)
{
    List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
    List<string> classesToAdd = args.Where(x => !classes.Contains(x)).ToList<string>();
    classes.AddRange(classesToAdd);
    control.CssClass = String.Join(" ", classes);
}
public static void RemoveCssClass(this WebControl control, params string[] args)
{
    List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
    classes = classes.Where(x => !args.Contains(x)).ToList<string>();
    control.CssClass = String.Join(" ", classes);
}

The methods are simply used to add or remove CSS classes from WebControls (from where Button s, Label s, Panel s etc. all inherits) like myButton.AddCssClass("class1", "class2"); 这些方法只是用于从WebControls (从Button s, Label s, Panel s等继承)添加或删除CSS类,如myButton.AddCssClass("class1", "class2"); or myButton.RemoveCssClass("class2"); myButton.RemoveCssClass("class2"); .

It might very well be a bit overhead but managing the CssClass property can also be a bit of a hassle as you´re forced to handle the whitespaces on your own. 它可能有点开销,但管理CssClass属性也可能有点麻烦,因为你被迫自己处理空白。

How many times haven´t you seen this one, for example? 例如,你有多少次看过这个?

string myCssClass = "class1";
myButton.CssClass += " " + myCssClass;

Please feel free to improve the methods! 请随意改进方法! :) :)

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

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