次のように、li タグに css クラスを追加します。
liComPapers.Attributes.Add("class", "NoDisplay");
この特定のクラス (NoDisplay) をコードの別の場所にある li タグから削除する方法はありますか?
次のコードを試しましたが、機能しません。
liComPapers.Attributes["class"] = "";
ありがとう
私はあなたのコードをテストするためのサンプルを作成しました、そして次の部分があなたが望むことを正確に行うことを発見しました:
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);
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>
推奨される方法
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());
liComPapers.Attributes.Remove("class");
特定のliタグのCSS属性を削除できます
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.