1

page_loadイベント内でサーバー側のJavaScript(onclick)とC#を使用して、ラベルのテキストを変更しようとしています。たとえば、次のようなものを書きたいと思います。

Label1.Attributes.Add("onclick", "Label2.text='new caption'")

誰かがこれの正しいコードを知っていますか?また、このタイプのコードは何を参照していますか。それは単なるJavaScriptまたはC#のJavaScriptですか、それとも特定の名前がありますか?最後に、C#で使用するcontrol.attributes.add( "event"、 "syntax")コードの選択肢をリストした本またはオンラインリソースはありますか?

4

2 に答える 2

2

There is no server-side Javascript (unless you change to a platform other than ASP.NET where you actually use Javascript as server language). What you are doing is adding an attribute to the html tag, and the code will be executed entirely on the client side.

First, let's look at how it's done in HTML without the server side code and server side controls:

<span onclick="document.getElementById('Label2').innerHTML='Thank you';">Click me</span>
<span id="Label2"></span>

To use Label controls instead, setting the onclick attribute from server side code, you would do like this:

Label1.Attributes.Add("onclick", "document.getElementById('Label2').innerHTML='Thank you';");

This will work as long as the controls are not inside a naming container. If they are, the id of the controls are prepended with the name of the container to keep them unique, so you need to use the ClientID property to find out what their final id is:

Label1.Attributes.Add("onclick", "document.getElementById('" + Label2.ClientID + "').innerHTML='Thank you';");

The ClientID always contains the id that you can use to access the element from Javascript, so the last code always works regardless if the control is in a naming container or not.

To find out what attributes you can use, you should look at the HTML documentation, for example the Internet Explorer documentation for the span element. When looking at the documetation for a specific feature, notice the Standards Information, as that will tell you if it works in any browser or just in Internet Explorer.

于 2009-05-09T23:25:57.423 に答える
1

The code above adds JavaScript to a server control rendered on the client. Take a look at this MSDN article - Using JavaScript Along with ASP.NET for more information.

IIRC, you will need to reference Label2 by its ClientID and will need to write some JavaScript to change the label's text value (I think ASP.NET labels get rendered as <span> tags).

于 2009-05-09T23:30:06.667 に答える