This article is a companion to. Net study notes-detail questions (http://www.cnblogs.com/zhouhb/archive/2011/02/17/1957336.html), record JavaScript Study Notes-details! Sometimes, Details determine success or failure!
(1) use JavaScript in ASP. NET
<SCRIPT type = "text/JavaScript">
Function validate ()
{
If (document. getelementbyid ("<% = txtusername. clientid %>"). value = "")
{
Alert ("Enter the user name! ");
Return false;
}
Else if (document. getelementbyid ("<% = txtpassword. clientid %>"). value = "")
{
Alert ("enter the password! ");
Return false;
}
}
</SCRIPT>
<Asp: button id = "btnlogin" runat = "server" text = "login" width = "47px" onclientclick = "Return validate ()"/>
If the following JavaScript code is used:
If (document. getelementbyid ("txtusername"). value = "") {alert ("Enter the user name! "); Return false;} can also run. However, it is a coincidence that the clientid of the txtusername control happens to be txtusername. If you place the control in the content page, for example:
<Asp: Content ID = "content2" contentplaceholderid = "contentplaceholder1" runat = "server">
<Asp: Panel id = "Panel1" runat = "server">
<Asp: textbox id = "txtusername" runat = "server"> </ASP: textbox>
<Asp: button id = "btnlogin" runat = "server" text = "login" width = "47px" onclientclick = "Return myvalidate ();"/>
</ASP: Panel>
</ASP: content>
If you run the command, an error is returned. This is because the clientid of the txtusername control is changed to contentplaceholderpolictxtusername, which is no longer txtusername.
So the correct method is:
Document. getelementbyid ("<% = txtusername. clientid %>"). Value
(2) change the color of the table on different rows
<SCRIPT type = "text/JavaScript">
Window. onload = function (){
VaR OTB = Document. getelementbyid ("tbstu"); // obtain the table
For (VAR I = 0; I <OTB. Rows. length; I ++ ){
If (I % 2 = 0)
OTB. Rows [I]. classname = "Trodd ";
}
}
</SCRIPT>
(3) control the display or hiding of HTML Objects
Function Change ()
{
VaR BTN = Document. getelementbyid ("button2 ");
If (BTN. style. Display = "")
BTN. style. Display = "NONE ";
Else
BTN. style. Display = "";
}
(4) dynamic style Switching
4.1 Use the style attribute of HTML elements
<SCRIPT type = "text/JavaScript">
Function changebackcolor ()
{
VaR DIV = Document. getelementbyid ("div1 ");
Div. innerhtml = "changebackgroundcolor ";
Div. style. backgroundcolor = "green ";
}
</SCRIPT>
// Html code
<Div id = "div1" onclick = "changebackcolor (); alert ('changebackgroundcolor')">
<P> click me! </P>
</Div>
4.2 Use the classname attribute of the HTML Element
<Style type = "text/CSS">
. Backcolor
{
Background-color: green;
Font-size: 20px;
Color: red;
}
</Style>
<SCRIPT type = "text/JavaScript">
Function changebackcolor ()
{
VaR DIV = Document. getelementbyid ("div1 ");
Div. innerhtml = "changebackgroundcolor ";
// Div. style. backgroundcolor = "green ";
Div. classname = "backcolor ";
}
</SCRIPT>
The HTML code is the same as above.