9

次のように、li タグに css クラスを追加します。

liComPapers.Attributes.Add("class", "NoDisplay");

この特定のクラス (NoDisplay) をコードの別の場所にある li タグから削除する方法はありますか?

次のコードを試しましたが、機能しません。

liComPapers.Attributes["class"] = ""; 

ありがとう

4

6 に答える 6

7

私はあなたのコードをテストするためのサンプルを作成しました、そして次の部分があなたが望むことを正確に行うことを発見しました:

 var newClassValue = liTest.Attributes["class"].Replace("NoDisplay", "");
 liTest.Attributes["class"] = newClassValue;

テストと動作:( 何らかの理由で)上記のコードが機能しなかった場合は、クラス値を置き換える別の方法で、前と同様の別のアプローチをお勧めします

var newClassValue = liTest.Attributes["class"].Replace("NoDisplay", "");
liTest.Attributes.Remove("class");
liTest.Attributes.Add("class",newClassValue);
于 2012-11-22T23:47:04.773 に答える
7

If I understand correctly:

If you wish to remove only NoDisplay, you could replace that part of the string with an empty string:

liComPapers.Attributes["class"] = liComPapers.Attributes["class"].Replace("NoDisplay", "");

However, .Add("class", "NoDisplay") won't add a new class to your class attribute. It will create a new class attribute with the value NoDisplay. Therefore if your markup is currently:

<li class="myClass"></li>

It would become:

<li class="myClass" class="NoDisplay"></li>

This is invalid markup.

To append new classes to an element with existing classes, you can do:

liComPapers.Attributes["class"] += " NoDisplay";

This would then render:

<li class="myClass NoDisplay"></li>
于 2012-11-22T23:31:41.863 に答える
2

推奨される方法

liComPapers.Attributes["class"] = liComPapers.Attributes["class"].Replace("NoDisplay", "");    

文字列を含む別の css クラスを切り取り"NoDisplay"、エラーが発生します

例えば

<li class="NoDisplay AnotherClass-NoDisplay"></li>

になる

<li class=" AnotherClass-"></li>

したがって、より安全な解決策は

liComPapers.Attributes["class"] = String.Join(" ", liComPapers.Attributes["class"]
                                        .Split(' ')
                                        .Where(x => x != "NoDisplay")
                                        .ToArray());
于 2014-11-10T10:21:02.823 に答える
2
liComPapers.Attributes.Remove("class");

特定のliタグのCSS属性を削除できます

于 2013-07-24T11:49:27.827 に答える
1

Try the following:

liComPapers.Attributes.Remove("class");

AttributeCollection.Remove Method

于 2012-11-22T23:30:59.463 に答える
0

Your code seems right. Check this link: How to: Set HTML Attributes for Controls in ASP.NET Web Pages

Are you using callbacks/ajax? Maybe you are not considering that..

Try to do a simple page with only one control and put a button to do a postback , on the button's click event (server side) assign the attribute the same way you did before. It should works.

于 2012-11-22T23:31:08.667 に答える