Detailed description of Script tag and HTML page access

Source: Internet
Author: User
Tags image flip

Copy codeThe Code is as follows:

<Script type = "text/javascript">
Var img2 = document. getElementById ("img2 ");
Alert (img2.onmouseover );
// Output to slices
</Script>

IE output:

Firefox:

Copy codeThe Code is as follows:

<Script type = "text/javascript">
Var img1 = document. getElementById ("img1 ");
Img1.onmouseover = rotate;
Function rotate (){
This.src?'{yylklshmyt20090217.jpg ';
}

Var img1 = document. getElementById ("img1 ");
Img1.onmouseover = onmouseover;
Function onmouseover (event ){
This.src?'{yylklshmyt20090217.jpg ';
}

// In fact, document. getElementById ("img1"); an object is equivalent to the following:
/* Var img1 = {src: "1_ender1000.jpg ",
Id: "img1 ",
Alt :"",
Title: "reverse image"
}*/
</Script>

Copy codeThe Code is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "WebApplication1.WebForm1" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
<Script type = "text/javascript">
// Loop all attributes of the img image. You can see many attributes that are not defined.
Window. onload = repeat;
Function repeat (){
Var img1 = document. getElementById ('img1 ');
For (var I in img1 ){
Alert (I + ":" + img1 [I]);
}
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>

</Div>
</Form>
</Body>
</Html>

Script tag and access HTML page
Script tag
The script tag is used to embed some executable scripts in the HTML page.

<Script>
// Some script goes here
</Script> the script tag has three special attributes (of course, attributes such as id and class also exist. Almost every element in the HTML page can have the class and id attributes)

<Script language = "JavaScript"> // The language attribute specifies the language of the script contained in the tag.
// It has three common values: JavaScript, JScript, and VBScript.
// Some script goes here
</Script>
// Only IE can recognize JScript. other browsers will ignore the content in this label.
// For VBScript, only IE on Windows can recognize and run
// However, the language attribute is replaced by the type attribute in XHTML.
<Script type = "text/javascript"> // The value has also changed. For example, text/javascript, text/jscript, text/vbscript
// Some script goes here
</Script> in a Web browser, we only use JavaScript, And the type attribute is set to text/javascript. in fact, JavaScript is very popular and almost becomes synonymous with scripts. In Web browsers, even if the script tag does not add any attributes, the browser regards it as JavaScript.

<Script>
Alert ("Hello! ");
</Script>
// The code above will be executed in JavaScript
// Even if there is IE, the script block without declaration will be executed as JavaScript instead of VBScript.
<Script>
Msgbox "Hello! "
</Script>
// The code above will also report an error in IE, and IE will regard it as JavaScript before it is executed on the HTML page. Some labels usually add attributes such as onclick and onmouseover, this is an event binding (for details about events, don't Worry ). specifies the JavaScript code to be executed when something happens to an element on an HTML page (or other client scripts)

The above Code will display an image on the HTML page. When you click it with the mouse, a pop-up window will appear, showing 'you have hurt me! ', The value of the onclick attribute is actually a piece of JavaScript code. This is the event. Below are some other simple events.

Onclick: Execute once when you click the mouse.
Onmouseover: run the command once when the mouse is placed.
Onmouseout: run the command once when the mouse is removed.
Onmousedown, executed once when the mouse is pressed
Onmouseup: Execute once when the mouse is lifted (popped up)
Onmousedblclick: Run Once when you double-click the mouse.
Onload, executed once when the object is loaded
In the past, RollverImages (FLIP image), which was widely used on the Internet, was actually implemented by combining events such as onmouseover, onmouseout and simple JavaScript code.

Onmouseover = "this. src = '../images/over.jpg '"
Onmouseout = "this. src = '.. /images/out.jpg '"/> you may know that strings in attributes such as onmouseover will be executed as scripts when an event occurs, but the above Code looks very fuzzy.

// For ease of viewing, we extract them and put them below
This. src = '../images/over.jpg'
This. src = '.. /images/out.jpg 'after analyzing the above Code, we found that this is actually assigning a value to the src attribute of an object, but the problem is that we have not declared an object called this! In fact, this object is always an object that cannot be declared (this is the keyword). Here, this refers to "this", which refers to this tag! For elements in HTML, JavaScript automatically parses them into an object. For the following img tags, It is parsed into the following object:


// Note: in fact, this cannot be manually assigned or declared. this is only an example.
This = {
Src: "../images/stack_heap.jpg ",
Alt: "memory stack ",
Onclick: "alert ('Hello! ')",
TagName: "IMG"
};
// In fact, the img tag will be parsed into an object with src, alt, and other attributes. The src and alt attributes are written in HTML, the tagName is automatically generated by the system. It indicates the Tag Name of the tag! We can use the following code for testing:

naturally, we can also modify its value, so the image flip effect is successful.

Pay attention to binding such intra-row events.

<Head>
<Script>
Function myFn (){
Alert ("image loading is complete! ");
}
</Script>
</Head>
// ...... After several pieces of code
// execute a function when the image is loaded successfully.
The above code execution is fine, but the order is flipped (the script can be placed in any legal place)

// execute a function when the image is loaded successfully.
// ...... After several pieces of code
<Script>
Function myFn (){
Alert ("image loading is complete! ");
}
</Script> the HTML page is loaded and executed in the order from top to bottom. After the image is loaded successfully, the content in onload (a custom function) is executed ), however, because the script tag is not loaded after the following code, the error "myFn is undefined" occurs. This is why the script tag should be placed in the head part, because the head is in front of the body. When the element in the body is loaded, the script in the head must have been loaded.

However, with XHTML and "layer-3 separation", W3C launched DOM2. We need to bind events in another way to obtain HTML page elements. The preceding image is used as an example:

<Head>
<Script>
Var img = document. getElementById ("myImg"); // we get it by ID
// The document. getElementById method has a parameter, a string ID
// Then, img indicates the Image Tag object
Img. onclick = myFn;
/* We do not give the JavaScript code a string value to its onclick attribute.
Instead, it is directly assigned a function name.
You will also say, why not img. onclick = myFn ();
Because it is in the JavaScript code area
Adding "()" indicates executing this function, and then assigning the return value of this function to img. onclick */
Function myFn (){
Alert ("image loading is complete! ");
}
</Script>
</Head>
//.......

// We no longer add The onclick attribute, but give it an ID
However, if the above code is executed, an error will still occur, because HTML is loaded from top to bottom. When it is loaded to the script, the body part is below and has not been loaded yet, javaScript is automatically executed when the browser is loaded. at this time, the img with the ID of myImg on the page has not been loaded, so an error will occur; document. the getElementById method requires a string ID. If there is no element with ID on the page, it returns null (empty object). In the following row, img. onclick uses an empty object, so an error occurs here! The solution is to put the script location bound to the traditional in-row event in turn. Put the script behind the HTML element!


// ...... After several pieces of code
<Script>
Var img = document. getElementById ("myImg ");
// At this time, because the script tag is placed after the img tag, the img tag must have been loaded when it is loaded to the script.
Img. onclick = myFn;
Function myFn (){
Alert ("image loading is complete! ");
}
</Script> however, we recommend that you place the script in the head section! So, this requires the use of another event onload

Window. onload = initAll; // write all the code in a function and register it with the onload event attribute of the window object.
// Window Indicates the window object. As long as the window opens, it will always exist. When the page is loaded, the onload event on the window object will be triggered.
Function initAll (){
Var img = document. getElementById ("myImg ");
Img. onclick = myFn;
Function myFn (){
Alert ("image loading is complete! ");
}
} In this way, the code will not go wrong. No matter where the script is placed, initAll will be executed only after the page is loaded.

Access the HTML page: HTML DOM
Html dom treats the entire page as a document object, and the tags in HTML must be accessed through the document Object. Each tag in the document will be converted into an object.

<P class = "demo" title = "first section: DOM tree "id =" p1 "> we use a p tag for demonstration </p>. It is converted to the following object.

// Remember the object literal syntax.
{
TagName: "p ",
ClassName: "demo ",
Title: "First paragraph: DOM tree ",
Id: "p1 ",
InnerHTML: "We use a p tag for demonstration"
}
// You may wonder why the class attribute of the tag changes to the className attribute of the object instead of the class.
// Class is a reserved JavaScript word !!!
// TagName indicates its tag name, while innerHTML indicates its HTML code browsing. After converting HTML tags into such objects, accessing the tag attributes or content in JavaScript is much simpler, but the question is how to access this object !!

// Add an ID to the tag, and then use the document. getElementById method to access it.
Window. onload = initAll; // note that you should put the code for accessing the HTML page on the onload event processing of the window!
Function initAll (){
Var p = document. getElementById ("p1 ");
Alert (p. className );
Alert (p. tagName );
Alert (p. title );
Alert (p. id );
Alert (p. innerHTML );
} Accessing the HTML page is that simple! After obtaining an element, you can not only read its property value, but also set its property value!

Window. onload = initAll;
Function initAll (){
Var p = document. getElementById ("p1 ");
P. title = "JavaScript ";
P. className = "load"; // We can change its style.
} With this, we can already do some exciting things!

// Some CSS
. Over {
Color: red;
Background: blue;
Font-size: larger;
}
. Out {
Color: black;
Background: white;
Font-size: smaller;
}
. Click {
Color: yellow;
Background: yellow;
Font-size: 12px;
}
// HTML code
<P id = "p1" class = "out"> A large line of text, all of which are common text! </P>
// JavaScript code
Window. onload = initAll;
Function initAll (){
Var p = document. getElementById ("p1 ");
P. onclick = clickFn; // except for the intra-row registration method, the event registration method has fewer parentheses. The others are the same.
P. onmouseover = overFn;
P. onmouseout = outFn;
}
Function clickFn (){
This. className = "click"; // here, this is also available
// Note that it is className, not class
}
Function overFn (){
This. className = "over ";
}
Function outFn (){
This. className = "out ";
Of course, the webpage element will not stop this kind. Doc ument. the getElementsByTagName method can also obtain page elements, which are obtained through HTML tags rather than IDs. because an HTML page has a unique ID and most tags are the same, the getElementsByTagName method has only one parameter, that is, the tagName in the string format ), the returned value is an array-like HTML element list.

Window. onload = initAll; // you still need to write it in the window. onload event processing function.
Function initAll (){
Var pList = document. getElementsByTagName ("P ");
// Why should I use uppercase P? In fact, it can be written in lower case p, not case sensitive. However, because the tagName of an object is reported in upper case ....
Alert (pList. length); // similar to an array, length reports the number of elements and the number of p tags on the page.
Alert (pList [0]. innerHTML); // This way to access the first p element
} In addition, for the document. getElementsByTagName method, you can also use a "*" number as a parameter to obtain all elements of the page, similar to wildcards in CSS.


Window. onload = initAll;
Function initAll (){
Var allThings = document. body. getElementsByTagName ("*");
// The getElementsByTagName method can be called on any DOM element. When this method is called on the body, tags outside the body will not be obtained.
Alert (allThings. length); // The number of labels on the page, the report is as much (including DOCTYPE)
Alert (allThings [3]. innerHTML); // access the fourth element.
} Others-javascript: pseudo Protocol
The pseudo-protocol is used for associating applications, unlike the real existence of http: //, https: //, and ftp: // on the Internet. for example, tencent: // (associated with QQ), data :( base64 encoding is used to output binary files in the browser), and javascript:

You can enter "javascript: alert ('js! '); ", After you click it, you will find that the code behind javascript is executed as JavaScript and the result value is returned to the current page.

Similarly, we can use the javascript pseudo protocol in the href attribute of tag.

<A href = "javascript: alert ('js! '); "> </A>
// Click this link. The browser does not jump to any page, but displays a pop-up window. However, javascript: the pseudo Protocol has a problem and returns the execution result to the page of course.

<A href = "javascript: window. prompt ('input content will replace the current page! ', '');"> A </a> the solution is simple.

<A href = "javascript: window. prompt ('input content will replace the current page! ', ''); Undefined;"> A </a>
// Add undefined to the end. Although the javascript pseudo protocol provides some flexibility, try not to use it on the page! For JavaScript debugging, the javascript pseudo protocol is very useful!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.