简体   繁体   中英

How can I change the class of an element with jQuery?

In my ASP.NET app I'm using AJAX and some web services to update an unknown number of instantiated user controls (hence the reason I'm using FindControl below).

When a function returns a result, I'm trying to change the color of a label control. This works:

$get("<%= me.FindControl("lblName").ClientID %>").style.color = 'red';

Now I would like to be able to specify the colors from a CSS file.

.MyRed 
{
    color:Maroon;
}

And here is the part I can't figure out. I've tried using addClass and toggleClass but the browser reports "Object doesn't support property or method 'toggleClass'" etc.

$get("<%= me.FindControl("lblName").ClientID %>")......  = '.MyRed';

As always, thanks in advance!

$get is Microsoft specific but returns a DOM object..

So you can use this DOM object with jQuery like this:

$($get("<%= me.FindControl("lblName").ClientID %>")).toggleClass('MyRed');

Hope it helps...

Since you appear to be using the ASP.NET AJAX library , you can call Sys.UI.DomElement.addCssClass() :

Sys.UI.DomElement.addCssClass(
    $get("<%= me.FindControl("lblName").ClientID %>"), "MyRed");
$('#<%= me.FindControl("lblName").ClientID %>').addClass('myRed');

如果您想使用jQuery,则需要以下代码:

$("#<%=lblName.ClientID %>").addClass("MyRed");

what is $get ? if you're trying to use jQuery you need to either use $ or the jQuery object.

$('#<%= me.FindControl("lblName").ClientID %>').removeClass("removeMe").addClass("addMe")

如果在选择器上使用id,则应在id值之前添加“#”字符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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