/Example/ /If the prototype method is redefined by itself and then the prototype method of the base class will not change as it changes/
『
function Person(name,sex) { //Constructor of Person class
= name;
= sex;
}
= 12; // Assign values to the properties of the prototype object corresponding to the prototype attribute of the Person class,
//Equivalent to adding attributes to the parent class of Person class
= function() { //Add method to the parent class of Person class
alert(+"_"++"_"+);
};
var p1 = new Person("name1","male"); //The age attribute of p1 inherits the parent class of the child Person class (i.e., the prototype object)
var p2 = new Person("name2","male");
(); //name1_male_12
(); //name2_male_12
= 34; //Change the age attribute of the p1 instance
(); //name1_male_34
(); //name2_male_12
= 22; //Change the age attribute of the superclass of Person class
(); //name1_male_34 (The age attribute of p1 does not change with the change of prototype attribute)
(); //name2_male_22 (The age attribute of p2 has changed)
= function() { //Change the print method of p1 object
alert("i am p1");
}
(); //i am p1(The method of p1 has changed)
(); //name2_male_22 (the method of p2 has not changed)
= function() { //Change the print method of Person superclass
alert("new print method!");
}
(); //i am p1 (p1's print method is still its own method)
(); //new print method!(P2's print method changes with the change of superclass method)
』
JS Advanced Programming Chapter 4 BOM ↑↓←→
BOM (browser object model)
Browser objects are divided into
{
1. Window window object (including the entire browser)
2. Location address object (mainly including address bar)
3. Document document object (where it is displayed when output using(), occupying most of the browser's space)
4. Form form object (included in document object and composed of forms)
}
//Window object (Window object represents the entire browser window, but does not have to represent the content contained therein, it is mainly used to resize the browser)
{
The window object represents the entire browser window
moveBy(dx,dy) - move the browser window horizontally by dx pixels and vertically by dy pixels. The value of dx is negative, move the window to the left, the value of dy is negative, move the window up.
moveTo(x,y) - Move the browser window so that its upper left corner is located at (x,y) of the user's screen. Negative numbers can be used, but this will move some windows out of the visual area of the screen.
function click1() {
(()*1000,()*1000);
}
resizeBy(dw,dh)—Relative to the current size of the browser window, adjust the width of its port by dw pixels and the height by dy pixels. dw is a negative number, reduce the width of the window, dy is a negative number, and reduce the height of the window.
resizeTo(w,h)—Adjust the width of the window to w and the height to h. Negative numbers cannot be used.
The method of window object is mainly used to provide information or input data and create a new window. Create a new window Open() Use the (parameter table) method to create a new window. The parameter table provides the main features of the window, documents and window naming.
open("open url of window", "window name", "window feature")
The characteristics of the window are as follows and can be combined any:
top=# Number of pixels at the top of the window leaving the top of the screen
left=# The number of pixels on the left end of the window leaving the left end of the screen
width=# window width
height=# The height of the window
menubar=... Does the window have a menu, value yes or no
toolbar=... Does the window have a toolbar, take the value yes or no
location=... Does the window have an address bar, value yes or no
directories=... Is there a connection area in the window, and the value yes or no
scrollbars=... Does the window have scrollbars, take the value yes or no
status=... Does the window have a status bar, and the value yes or no
resizable=... window is not resized, the value yes or no
}
//Dialogue
{
alert ("m prompt message") //Displays a dialog box containing the message.
alert("First Dialog Box"); // A warning box pops up
confirm ("prompt message") // Display a confirmation dialog box containing a confirmation cancel button //confirm: OK; make consolidation; approve
If(confirm("Are you sure?")) () writes the prompt message. This method will return a Boolean value. Click OK to return to TRUE, click Cancel to return to FALSE
{
alert("yes you clicked"); //Usually used, the information displayed when you click OK
}
else
{
alert("you click no"); //The information displayed when you click Cancel
}
Prompt ("Prompt message") //The prompt message box pops up
open ("url","name") //Open a new window with the specified name and load the document specified by the given URL; if no URL is provided, open a blank document, and add another parameter to the description (width and height of the opened browser...)
close ( ) //Close the current window
/example/
<script type="text/javascript" language="javascript">
var win;
function openwindow() {
win = open("","Sina","height=150,width=300,top=10,left=10,resizable=yes");
}
function closewindow() {
();
}
</script>
</head>
<body>
<input type="text" />
<script language="javascript" type="text/javascript">
Default value in text box
↓
("txtname").value = prompt("Please enter your name","qw");
↑
Script prompt text
</script>
<input type="button" value="Open a new window" onclick="openwindow()"/>
<input type="button" value="Close the window that just opened" onclick="closewindow()"/>
</body>
}
defaultStatus status: Set the status bar at the bottom of the browser. defaultStatus is persistent and status is temporary. Note: By default, IE7 sets "Allow status bar to update through scripts" to be disabled. You can modify this setting in Internet Options-《Security
『
<script language="javascript" type="text/javascript">
function mystatus()
{
// = "Did you pay attention to my existence??";
= "Did you pay attention to my existence?";
}
</script>
</head>
<body onload="mystatus()">
<a href="" onmouseover="='Did you pay attention to my changes??';return true" onmouseout="='Did you pay attention to my existence??';return true"></a>
↑ ↑
Note that the single quote semicolon and return true cannot be omitted. Return true can prevent the address from appearing in the status bar.
</body>
』
history
『
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function go_destination()
{
(-1); //(-1) and () have the same effect
}
function go_back()
{
();
}
</script>
</head>
<body>
<input type="button" onclick="go_destination()" value="Previous page" />
<input type="button" onclick="go_back()" value="Previous page" />
</body>
The Back ( ) method is equivalent to the back button
The forward ( ) method is equivalent to the forward button
go (1) represents going to 1 page, which is equivalent to the forward( ) method;
go(-1) represents 1 page back, which is equivalent to the back( ) method;
』
Document object
『
alinkColor Set or retrieve the colors of all active links in the document
bgColor Set or retrieve the background color of the Document object
body Specifies the beginning and end of the document body
linkColor Set or retrieve the color of the document link
location contains information about the current URL
title contains the title of the document
url Set or retrieve the URL of the current document
vlinkColor Set or retrieve the color of the links visited by the user
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function showTitle()
{
="I haven't been a big brother for many years"; //Set the title
}
function change(color)
{
=color;
}
</script>
</head>
<body>
<input type="button" onclick="showTitle()" value="Click me to display the title" />
<h2>Move over and I will change the color show for you</h2>
<span onmouseover="change('#CCCCCC')">Go red</span>
<span onmouseover="change('blue')">Go red</span>
<span onmouseover="change('yellow')">Go red</span>
<img src="../js02/img/"alt="" height="200" width="200" onmouseover="alert([0].src)" />
<img src="../js02/img/"alt="" height="200" width="200" onmouseover="alert([1].src)" />
</body>
Cookie attribute
Here we mainly introduce the cookie attributes. Cookies are a small text file stored on your machine when you browse a website. It records your user ID, password, web pages you have browsed, and stayed. When you come to the website again, the website can make corresponding actions by reading the cookie and learning about your relevant information, such as displaying a slogan that welcomes you on the page, or allowing you to log in directly without entering your ID or password, etc.
The cookie attribute also contains some of its own attribute values:
expires: Used to set the expiration time of the cookie.
domain: Used to set the scope of the website domain name that cookies work.
path: Used to set the website path to which cookies work.
secure: If this property is set, the value of the cookie can only be read under a very high security setting.
The purpose of cookies is to bring convenience to users and add value to the website. The cookie attribute also contains some of its own attribute values:
We can set a certain cookie value through operations.
』
Location object
『
property
host Set or retrieve the host name and port number of the location or URL
hostname Sets or retrieves the hostname part of the location or URL
href Set or retrieve the complete URL string
method
assign("url") Loads the new HTML document specified by the URL.
reload() reload the current page
replace("url") replaces the current document by loading the document specified by the URL
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function jump()
{
=;
}
function jump1()
{
(); //Note that the string placed in replace is used for use "" //Replace() does not record history, that is, it cannot be backed after clicking.
}
function jump2() {
(); //Record history and you can back down
}
function showHost()
{
alert();
}
function showHostName()
{
alert();
}
function reLoad() {
();
}
</script>
</head>
<body>
<form name="myform" action="">
<select name="menu" onchange="jump2()"><!--Note the difference in jump1--> //<select>: drop-down menu <option>Each option
<option >-Please select-</option>
<option value="">Inuyasha</option>
<option value="">Seshomaru</option>
</select>
<input type="button" value="Show host name and port number" onclick="showHost()" />
<input type="button" value="Showhostname" onclick="showHostName()" />
<!--<input />-->
<input type="button" value="refresh" onclick="reLoad(true)" /><!--true means loading false from the server means loading from the cache-->
</form>
</body>
』
Navigator //Navigator object is automatically created by JavaScript runtime engine and contains information about the client browser (basically not required)
『
(, "<br />"); //Internal code name related to the browser
(, "<br />"); //The official name of the browser
(, "<br />"); //The version number of the browser
(,"<br />");//FireFox does not support it
(, "<br />"); //FireFox does not support it, it returns the CPU model of the user's computer, and usually the Intel chip returns "x86"
(,"<br />");//IE does not support it
(, "<br />"); // The operating system platform where the browser is running
();//Microsoft's unique object,
/show/
Mozilla
Microsoft Internet Explorer
4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)
zh-cn
x86
undefined
Win32
Microsoft Internet Explorer
』
//screen object
『
availHeight - The height of the screen (in pixels) that the window can use, which includes the space required by operating system elements such as the Windows toolbar.
availWidth – The width of the screen (in pixels) that the window can use.
colorDepth—The number of digits that the user represents the color. Most systems use 32 bits.
height – The height of the screen, measured in pixels.
width - the width of the screen, in pixels
(0,0); //Adjust the browser to the top left corner
(,,"<br />"); //Set the screen to maximize
( + " " + , "<br />"); //Output display screen's maximum available width and height "The start status bar accounts for a part"
( + " " + , "<br />"); //The maximum height and width of the screen
(" " + , "<br />");
』
//Open a new form
『
<SCRIPT language="JavaScript" >
function openwindow( ) {
var newWindow = ("about:blank", "newWindow", "toolbars=yes, scrollbars=yes, location=yes,statusbars=yes,menubars=yes,resizable=yes,width=650,height=150"); // If the things in () are written correctly, otherwise you can't read them. If you really can't use "",",",""" is OK.
(); //Fluid opens
("<html><head><title>The best famous tea--Tieguanyin</title></head>");
("<body><h1>Hello, come and try some Tieguanyin? <a href=''>Come</a> <a href=''>No</a></h1></body></html>");
(); //Fluid Close
}
</SCRIPT>
</head>
<body onload="openwindow()">
』
//Transfer value across forms↑↓←→
『
Main form
『
<title>Unt title page</title>
<script type="text/javascript" language="javascript">
function aa()
{
open("","aaa","");
}
</script>
</head>
<body>
<form name="f1" action="" method="post">
↑
It's name, not id, there will be errors when using id
<input type="text" name="t1"/>
<button onclick="aa()">sdf</button>
</form>
</body>
』
Subform ()
『
<title>Unt title page</title>
<script type="text/javascript" language="javascript">
function bb()
{
document.f1.=.f1.;
↑
All the things behind f1 cannot be clicked out, so I will force it to hit
}
</script>
</head>
<body onload="bb()">
<form name="f1" action="" method="post">
<input type="text" name="t2"/>
</form>
</body>
』
』
JS Chapter 5 DOM (Text Object Model) ↑↓←→
//Node Type
『
1. Element nodes
2. Text nodes
<p>Paragraph</p> //<p> is an element node, and "paragraph" is a text node
』
//Three properties of node
『
nodeName node element name
nodeType node element type (1-12)
The value of nodeValue node element
1 element_node 2 attribute_node 3 text_node
4 cdata_section_node 5 entity_reference_node 6 entity_node
7 processing_instruction_node 8 comment_node 9 document_code
10 document_type_node 11 document_fragment_node 12 notation_node
"example"
『
<a href="">Journey to the stars</a>
-------------------------------------------------
External JS scripts:
addLoadListener(init);
function init()
{
var elementRef = ("sirius");
= "sdfsd"; //Change "Journey to the stars" dynamically to "sdfsd"; note that you should add "firstChild"
alert("The element is:" + ); //Show: A
alert("The element is:" + ); //Show: 1
alert("The element is:" + ); //Show: sdfsd
return true;
}
function addLoadListener(fn)//Register event function
{
if(typeof !="undefined")
{
("load",fn,false);
}
else if(typeof !="undefined")
{
("load",fn,false);
}
else if(typeof !="undefined")
{
("onload",fn);
}
else
{
var oldfn=;
if(typeof !="function")
{
=fn;
}
else
{
=function()
{
oldfn();
fn();
};
}
}
}
』
』
Access elements in the DOM
『
getElementById can be passed through a unique ID attribute value.
getElementById is very suitable for finding a single element
<a href="">Journey to the stars</a>
var elementRef = ("sirius");
"example"
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript" src="javascript/">
</script>
<link rel="Stylesheet" type="text/css" href="css/" />
</head>
<body>
<h1>Accessing elements</h1>
<ul>
<li><a href="" name="myLink">Sirius</a></li>
<li><a href="" name="myLink">Canopus</a></li>
<li><a href="" name="myLink">Arcturus</a></li>
<li><a href="" name="myLink">Vega</a></li>
</ul>
</body>
</html>
--------------------------------------------------------
Contents of external JS scripts:
function init()
{
var anchors=("myLink");
for(var i=0;i<;i++)
{
anchors[i].className="starLink";
}
//return true;
}
"example"
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function myCopy() {
var textBox1=("txt1");
var textBox2=("txt2");
=;
↑
The text in both text boxes is the same
}
</script>
</head>
<body>
<form action="" method="post">
<input />
<input type="button" value=">>>" onclick="myCopy()" /> //If the onclick() function wants to call more than two events, use ";" between the two events to separate them
↑
Words displayed on the button
<input />
</form>
</body>
</html>
』
JavaScript provides a method to return a set of elements by tag names: getElementsByTagName.
<a href="">Sirius</a>
<a href="canopus .htm">canopus </a>
<a href="arcturus .html">arcturus </a>
<a href=“vega .html”>vega </a>
var anchorArray = ("a");
"example"
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function myCopy()
{
var myArray = ("input");//Returns the element collection, the name of the tag is placed in (), remember to use ""
var h2 = ("h2");
for(var i=0;i<;i++)
{
if (myArray[i].type == "text") {
myArray[i].value=h2[0].innerHTML; //"innerHTML" means the text contained in the middle of <h2></h2>. If you can't click it, you can only hit it hard.
}
}
}
</script>
</head>
<body>
<form action="" method="post" >
<h2 >getElementsByTagName</h2><br />
<input name="txt1" />
<input name="txt1" />
<input name="txt1" />
<input type="button" value="Click Me" onclick="myCopy()" />
</form>
</body>
</html>
』
』
//The access order of nodes
『
Specify all child nodes of the node, including text nodes and all other elements //Usage: Nodes.childNodes Note: Don't add () after the typing
The first child node of the specified node
Specify the last child node of the node;
The superior node of the specified node;
The next sibling node of the specified node;
The previous sibling node of the specified node
"example"
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script type="text/javascript" language="javascript">
function myDominspector()
{
var DOMString="";
var DOMText="";
var demolist=("eventsList");
if(demolist==null) //Judge: Is the obtained set empty or is it successfully obtained?
{
return;
}
if(()) //hasChildNodes() This method can determine whether there are child nodes
{
var ch=; //If there are child nodes that use "ch" to obtain the set //Most of them are forced to be pressed, pay special attention to upper and lower case
for(var i=0;i<;i++)
{
DOMString+=ch[i].nodeName+"\n"; //Get the mark name of the child node
DOMText+=ch[i].; //Get the value of the child node, please add "firstChild" to it.
}
(DOMString);
(DOMText);
(ch[2].childNodes[0].); //Because "Class Table Item Three" uses nested tags, the above method is obtained by using "null"
}
}
</script>
</head>
<body>
<h1>Level 1 Title</h1>
<p>Paragraph</p>
<h2>Second-level title</h2>
<ul >
<li>List Item 1</li>
<li>List Item 2</li>
<li><a href="">List Item Three</a></li>
<li>List Item 4</li>
</ul>
<p>Paragraph</p>
<p>Paragraph</p>
<input type="button" onclick="myDominspector()" value="Click Me"/>
</body>
</html>
"show"
After clicking the button
LI LI LI LI List item 1 List item 2 null List item 4 List item 3
』
』
//Blank node
『
For some text-described DOM structures (such as HTML files), some browsers insert some blank nodes between element nodes.
For IE, all blank nodes are ignored
"example"
『
////////////// External js script:
addLoadListener(init); // Run this script when loading
function init() {
var star2 = ("star1").nextSibling; //Get the next brother node of "star1" - star2 (I think this is what it can be implemented in IE, but in Firefox, the corresponding blank node will be added, and the blank nodes obtained in Firefox are obtained here)
//alert();
if(=="3")//3 represents a text node (text_node), and a blank node is also a text node. If it is not a blank node, the nodeType here is 1 (element_node)
{
star2=;
}
= "starLink";
var temp = ; // documentElement represents HTML element
alert();
if ( == "3") {
temp = ;
}alert();
return true; // Add this sentence to the web page, even if there is an error, it will not report an error. You can continue to execute the following code
}
function addLoadListener(fn) //This function is verified whether the browser version is IE, Firefox or something else. You can copy it directly and use it
{
if(typeof !="undefined")
{
("load",fn,false);
}
else if(typeof !="undefined")
{
("load",fn,false);
}
else if(typeof !="undefined")
{
("load",fn);
}
else
{
var oldfn=;
if(typeof !="function")
{
=fn;
}
else
{
=function()
{
oldfn();
fn();
};
}
}
}
----------------------------------------------------
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript" src="javascript/">
</script>
<link rel="Stylesheet" type="text/css" href="css/" />
</head>
<body>
<h1>Accessing elements</h1>
<div >
<ul >
<li >Rigel</li>
<li >Altair</li>
<li >Betelgeuse</li>
</ul>
</div>
</body>
</html>
』
』
//Create element nodes and text nodes Selection of creation method
『
createElements is a function that creates new elements.
var newAnchor = ("a");
Create function createTextNode Create text node
var anchorText = ("monoceros");
There are 3 basic ways to insert new element nodes or text nodes into web pages
Put it to the end: appendChild () method //Usage: previous node.appendChild (name of the next node) Note: the name does not need to be expanded with ""; this method is to add the node to the back of "previous node"
Before putting it on a certain node: insertBefore () method //Usage: Parent node.insertBefore (new node, defined node) → → (display order): new node defined node
ReplaceChild () method //Usage: Parent node.replaceChild (new node, old node) → → → (display result): Replace the old node with the new node
"example"
『
Here is the content of the external JS script:
addLoadListener(init);
function init()
{
var anchorText=("monoceros"); //Create a text node
var newAnchor = ("a"); //Create an element node
="";//Add link attributes to the newly created hyperlink node
(anchorText); //Element nodes and text nodes connect to each other
var parent=("starLinks");
var newChild=(newAnchor); //Add the newly created node to the back of the original super connection
return true;
}
function addLoadListener(fn) //The following is to determine the browser type
{
if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('onload', fn);
}
else
{
var oldfn = ;
if (typeof != 'function')
{
= fn;
}
else
{
= function()
{
oldfn();
fn();
};
}
}
}
-----------------------------------------------------------
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript" src="javascript/"></script>
</head>
<body>
<h1>Creating elements and test nodes</h1>
<p >
<a href="">Sirius</a>
</p>
</body>
</html>
』
』
//Change the element type
『
There is no direct, simple way to change the type of an element.
The main means to change element types - cloning
Note: Be careful when changing the node structure of the DOM
"example"
『
Here is the content of the external JS script:
addLoadListener(init);
function init()
{
var div=("div");
var p=("starLinks");
for(var i=0;i<;i++)
{
var clone=[i].cloneNode(true);//true means the cloned child node itself
(clone);
}
//debugger;
=("id");
="starLink";
(div,p);
}
function addLoadListener(fn)
{
if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('onload', fn);
}
else
{
var oldfn = ;
if (typeof != 'function')
{
= fn;
}
else
{
= function()
{
oldfn();
fn();
};
}
}
}
-----------------------------------------------------------
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript" src="javascript/"></script>
<link rel="Stylesheet" type="text/css" href="css/" />
</head>
<body>
<h1>Changing the type of an element</h1>
<p >
<a href="">Sirius</a>
<a href="">Achanar</a>
</p>
</body>
</html>
』
』
//Delete an element or text node
『
The removeChild function can be used to delete any child node of the parent node and return the deleted object.
The deleted element no longer exists in the DOM: it only exists in memory
『Example 1』
『
var anchor=("sirius"); //Get the node object to be deleted
var parent=; //Find its parent node
var removedChild=(anchor); //Usage: Parent node.removeChild(child node object);
』
『Example 2』
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<link rel="Stylesheet" type="text/css" href="css/" />
<script language="javascript" type="text/javascript" src="javascript/"></script>
</head>
<body>
<h1>Removing an element</h1>
<div >
<p class="starLink">
<a href="">Aldebaran</a>
<a href="">Castor</a>
</p>
</div>
</body>
</html>
----------------------------------------------------------------------------
The following is the content of the plug-in js script:
var parent=("starLinks"); //Get the parent node object (f2)
var container=("starContainer"); //Get the parent node's object (f1)
while(>0)
{
([0],parent); //Put the child nodes in F2 and F1
}
(parent); //Delete F1 after the reciprocating is completed
』
』
//Read and write element attributes
『
The most commonly used part of HTML elements is its properties. JavaScript can not only read these attribute values, but also write back new values.
getAttribute can be used to read the value of an attribute, while setAttribute can be used to write a new value
『Example 1』
『
<a href="" title="Marssion">Antares</a>
---------------------------------------------------------------
Here is the content of the external JS script:
var anchor=("antares"); //Get the object to obtain the attribute
var anchorId=("id"); //Usage: Get the object to obtain the attribute.getAttribute("attribute name (note that ""add")")
var anchorTitle=("title");
alert("The anchor ID is:"+anchorId+"\nThe anchor title is:"+anchorTitle);
』
『Example 2』
『
<a href="" title="Marssion">Antares</a>
----------------------------------------------------------------
Here is the content of the external JS script:
var anchor=("antares"); //Get the object to obtain the attribute
("title",""); // Usage: Get the object to which the attribute is to be obtained.setAttribute("attribute name (note that ""add")", "The value to be assigned to the attribute name (note that ""add)")
var newTitle=("title"); //The new attribute value will overwrite the old attribute value
alert("The anchor title is:"+newTitle);
』
』
//Get all elements with specific attribute values
『
If you need to find all elements that satisfy the condition type="checkbox" in the input element
var inputs = ("input");
for (var i = 0; i < ; i++)
{
if (("type") == "checkbox")
{
...
}
}
Solution—getElementsByAttribute function
"example"
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript" src="javascript/">
</script>
</head>
<body>
<h1>Getting all element with a particular attribute value</h1>
<p >
<label for="test1">test1</label>
<a href="" title="sirius">Sirius</a>
<a href="" title="marssion">Marssion</a>
<a href="" title="marssion">Marssion</a>
<a href="" title="marssion">Marssion</a>
<a href="" title="marssion">Marssion</a>
<a href="" title="marssion">Marssion</a>
</p>
</body>
</html>
-------------------------------------------------------------
Here is the content of the external JS script:
addLoadListener(init)
function init() {
var anchors = getElementsByAttribute("title", "marssion"); //Get the set of elements with the attribute name "title" and the attribute value of "marssion". This method is defined below and just use it.
alert("There are " + + " elements with the title marssion");
var label = getElementsByAttribute("for", "test1");
alert();
}
function getElementsByAttribute(attribute, attributeValue) //This function determines whether the attributes and attribute values comply with regular expressions based on different browsers.
{
var elementArray=new Array();
var matchedArray=new Array();
if()
{
elementArray=;//IE gets all elements
}
else
{
elementArray=("*");//DOM gets all elements
}
for(var i=0;i<;i++)
{
if(attribute=="title")
{
var pattern=new RegExp("(^| )"+attributeValue+"( |$)");//Instantiate regular expression
if ((elementArray[i].getAttribute(attribute)))//Test whether it matches the expression
{
matchedArray[]=elementArray[i];
}
}
else if(attribute=="for")
{
if(elementArray[i].getAttribute("htmlFor")||elementArray[i].getAttribute("for"))
{
if(elementArray[i].htmlFor==attributeValue)
{
matchedArray[]=elementArray[i];
}
}
}
else if(elementArray[i].getAttribute(attribute)==attributeValue)
{
matchedArray[]=elementArray[i];
}
}
return matchedArray;
}
function addLoadListener(fn) //This function is to determine the browser model
{
if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('onload', fn);
}
else
{
var oldfn = ;
if (typeof != 'function')
{
= fn;
}
else
{
= function()
{
oldfn();
fn();
};
}
}
}
』
』
//Addition of class of element //Class css stylesheet
『
All the classes of elements can be accessed through the className property.
The value of this property is a string
"example"
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<link rel="Stylesheet" type="text/css" href="css/" />
<script language="javascript" type="text/javascript" src="javascript/"></script>
</head>
<body>
<h1>Adding and removing multiple classes to/from an element</h1>
<p>
<a class="starLink" href="">Sirius</a>
<a class="starLink" href="">Aldebaran</a>
</p>
</body>
</html>
-------------------------------------------------------------------------------------------------------------
Here is the content of the external JS script:
addLoadListener(init);
function init()
{
var sirius=("sirius");
var aldebaran=("aldebaran");
addClass(sirius, "important"); //The functions are all below, just use them. Both functions automatically verify the regular expressions.
removeClass(aldebaran,"starLink"); //The functions are all below, just use them.
return true;
}
function addClass(target,classValue) {
//debugger;
var pattern = new RegExp("(^| )" + classValue + "( |$)");
if(!())
{
if(=="")
{
=classValue;
}
else
{
+=" "+classValue; // Just use spaces to separate the names of the two style sheets.
}
}
return true;
}
function removeClass(target,classValue)
{
var removedClass = ;
var pattern = new RegExp("(^| )" + classValue + "( |$)");
if((removedClass))
{
="";
}
return true;
}
function addLoadListener(fn)
{
if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('load', fn, false);
}
else if (typeof != 'undefined')
{
('onload', fn);
}
else
{
var oldfn = ;
if (typeof != 'function')
{
= fn;
}
else
{
= function()
{
oldfn();
fn();
};
}
}
}
』
』
//Concept of events
『
JavaScript programs use event-driven programming model. When certain events occur in certain elements, the web browser will generate an event (event)
When multiple functions are called in the same event, use ";" to separate them.
』
// Event flow
『
Event flow means that multiple elements can respond to the same event on the page
Divided into two categories
『
1. Bubble event (IE) Return from the first place where the event occurred layer by layer
2. DOM events return from the top (HTML) layer by layer to the bottom
』
『
type
A string that declares the type of event that occurred. The value of this property is the event handler name that deletes the prefix "on" (such as "click" or "mouseover")
"example"
『
var sType=;
function handleEvent(oEvent)
{
if(=="click")
{
alert("Cilcked!");
}
else if(=="mouseover")
{
alert("Mouse Over!");
}
=handleEvent;
=handleEvent;
}
』
』
Copy the codeThe code is as follows:
Event example
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script>
function alert1(fg) {
("display").innerHTML+=fg+"<br />"
}
function checkbtn() {
switch () {
case 1:
alert1("left key");
break;
case 2:
alert1("right-click");
break;
case 3:
alert1("left key + right key");
break;
case 4:
alert1("middle key");
break;
case 5:
alert1("left key + middle key");
break;
case 6:
alert1("right key + middle key");
break;
case 7:
alert1("left key + middle key + right key");
break;
}
}
</script>
</head>
<body>
<div onmousedown="checkbtn()" oncontextmenu="return false" style="width:50px;height:50px; background-color:Lime; cursor:hand;">Click</div> //Only use div's onmousedown
<div ></div>
</body>
</html>
』
Copy the codeThe code is as follows:
Event listening
IE
[Object].attachEvent("on+eventName",fnHandler") //eventName: The name of the action fnHandler: Event function
[Object].detachEvent("on+eventName",fnHandler")
DOM
[Object].addEventListener("eventName",fnHandler,bCapture)
[Object].removeEventListener("eventName",fnHandler,bCapture)
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml" >
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
var fnClick=function()
{
alert("Clicked");
}
var fnClick1 = function() {
alert("body");
}
var fnClick2 = function() {
alert("html");
}
var fnLoad = function() {
var temp = ("btn1");
var temp1 = ("body1");
var temp2 = ("html1");
("click", fnClick1, true);
("click", fnClick2, true);
("click", fnClick, true); //false is used for bubbling stage true is used for capture stage
}
var fnDetachEvent=function()
{
var temp=("btn1");
("click",fnClick,true);
}
</script>
</head>
<body onload="fnLoad()" >
<input type="button" value="click me" />
<input type="button" value="detachEvent" onclick="fnDetachEvent()" />
</body>
</html>
-----------------------------------------------------------------------
[code]Example 2
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
var fnClick=function()
{
alert("Clicked");
}
var fnLoad=function()
{
var temp=("btn1");
("onclick",fnClick);
}
var fnDetachEvent=function()
{
var temp=("btn1");
("onclick",fnClick);
}
</script>
</head>
<body onload="fnLoad()">
<input type="button" value="click me" />
<input type="button" value="detachEvent" onclick="fnDetachEvent()" />
</body>
</html>
[/code]
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
var EventUtil=new Object;
=function(oTarget,sEventType,fnHandler){
if()
{
(sEventType,fnHandler,false);
}
else if()
{
("on"+sEventType,fnHandler);
}
else//If it appears, it is not IE or Firefox browser, execute this
{
oTarget["on"+sEventType]=fnHandler;
}
};
=function(oTarget,sEventType,fnHandler){
if()
{
(sEventType,fnHandler,false);
}
else if()
{
("on"+sEventType,fnHandler);
}
else
{
oTarget["on"+sEventType]=null;
}
};
function handleClick()
{
alert("Click");
var oDiv=("div1");
(oDiv,"click",handleClick);
}
=function(){
var oDiv=("div1");
(oDiv,"click",handleClick);
}
</script>
</head>
<body>
<div style="background-color:Red; width:100px; height:100px;"></div>
</body>
</html>
//Example (supplement)
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript">
function load() {
document.f1. = plead; //Note: document points out the corresponding name attribute, and the function called after the equal sign does not need to be added ()
}
function plead() {
= "Please Press Me!";
}
</script>
</head>
<body onload="load()">
<form name="f1" action="">
<input name="b1" type="button" value="Press Me" /> //Called through external events
</form>
</body>
</html>
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function handleEvent(oEvent)
{
var oTextbox=("txt1");
+="\n>"+; //Convert event to event type for output
}
</script>
</head>
<body>
<p>Type some characters into the first textbox.</p>
<p><textarea rows="15" cols="50"
onkeydown="handleEvent(event)" onkeyup="handleEvent(event)" onkeypress="handleEvent(event)"></textarea></p> //Note that the function passes the value and the event
<p><textarea rows="15" cols="50"></textarea></p>
</body>
</html>
Copy the codeThe code is as follows:
Show call events
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function oldHandle() {
alert("aa");
}
</script>
</head>
<body>
<form name="myForm" action="" method="post">
<input name="myButton" type="button" value="Click Me" onclick="oldHandle()" />
</form>
<script language="javascript" type="text/javascript">
();//Show the call event handler is called, but the onclick event is not raised.
//alert();
</script>
</body>
</html>
Copy the codeThe code is as follows:
Return value about event
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript">
function check() {
var textbox = ("txt");
if ( == "") {
alert("Text box is empty");
();
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form onsubmit="return check()"> <!--return Give the event a boolean return value, true means that execution can continue, FALSE means that execution stops (here check() is equivalent to a boll value)-->
<input type="text" /> //onsubmit is a form submission event
<input type="submit" value="Submit" />
<!--<input type="button" onclick="sd()" />-->
</form>
</body>
</html>
-----------------------------------------------------------------------------
[code]Example 2
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function confirmLink()
{
return confirm("Do you really want to visit "++" ?"); //This is an option with yesno The returned bool value indicates whether the function continues to execute
}
function confirmAllLinks()
{
for(var i=0;i<;i++)
{
[i].onclick=confirmLink; // Dynamically bind the onclick event. If true is returned, the link will be executed. If false returns, the link will not be executed.
} //To put it bluntly
Copy the codeThe code is as follows:
Event name = "boolean value (TRUE is executed, FALSE is not executed)"
}
</script>
</head>
<body onload="confirmAllLinks()">
<a href="" >Click me to see</a>
<a href="" >Click me to see</a>
<a href="" >Click me to see</a>
<a href="" >Click me to see</a>
<a href="" >Click me to see</a>
<a href="" >Click me to see</a>
</body>
</html>
[/code]
Copy the codeThe code is as follows:
About Loading
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
// =function() // If you uncomment, an error will occur, because the code is run one line by one and loaded here. Body has not yet loaded, so an error will occur using body
// { // This example will explain, even if you change the body to something else, it doesn't seem to work. I didn't try it
// alert("Loaded");
// }
</script>
</head>
<body>
This example won't work because it's assinging the <code>onload</code> event handler to the wrong place!
<script language="javascript" type="text/javascript">
=function() // Can be executed correctly because the body has been loaded
{
alert("Loaded");
}
</script>
</body>
</html>
『
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function handleEvent(oEvent)
{
var oTextbox=("txt1");
+="\n>"+; //See the explanation of type above
+="\n target is "+(||).id;
+="\n keyCode is "+; //This is the key code that declares the keydown and keyup events and the unicode characters of the keypress events. The character code can be converted into a string using the () method.
+="\n charCode is "+;
var arrKeys=[];
if() //shiftKey ctrlkey altkey These bool value attributes declare whether the Alt, Ctrl, and Shift keys are pressed and held when the mouse event occurs.
{
("Shift");
}
if()
{
("Ctrl");
}
if()
{
("Alt");
}
+="\n keys down are "+arrKeys+" Number is "+;
}
</script>
</head>
<body>
<p>Type some characters into the first textbox.</p>
<p><textarea rows="15" cols="50"
onkeydown="handleEvent(event)" onkeyup="handleEvent(event)" onkeypress="handleEvent(event)"></textarea></p>
<p><textarea rows="15" cols="50"></textarea></p>
</body>
</html>
』
『
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript" src="javascript/"></script>
<script language="javascript" type="text/javascript">
function load() {
var textbox = ("txt");
= function(oEvent) { // This is a function that controls the right click. If you return false, the right click will be disabled.
//debugger;
if (isIE) { //If the browser is disabled by ie, disable the right key of the text box
oEvent = ;
= false;
}
else {
();
}
}
= function(oEvent) { //Disable the right key outside the text box
if (isIE) {
oEvent = ;
= false;
}
else {
();
}
}
}
</script>
</head>
<body onload="load()">
<input value="abcd" />
</body>
</html>
-----------------------------------------------------------------------------------------------------
Contents in the "javascript/" script: This is to determine the specific browser type, just use it
var sUserAgent = ;
var fAppVersion = parseFloat();
function compareVersions(sVersion1, sVersion2) {
var aVersion1 = (".");
var aVersion2 = (".");
if ( > ) {
for (var i = 0; i < - ; i++) {
("0");
}
}
else if ( < ) {
for (var i = 0; i < - ; i++) {
("0");
}
}
for (var i = 0; i < ; i++) {
if (aVersion1[i] < aVersion2[i]) {
return -1;
}
else {
return 1;
}
}
return 0;
}
var isOpera = ("Opera") > -1;
var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false;
if (isOpera) {
var fOperaVersion;
if ( == "Opera") {
;
}
else {
var reOperaVersion = new RegExp("Opera (\\d+\\.\\d+)");
(sUserAgent);
fOperaVersion = parseFloat(RegExp["$1"]);
}
isMinOpera4 = fOperaVersion >= 4;
isMinOpera5 = fOperaVersion >= 5;
isMinOpera6 = fOperaVersion >= 6;
isMinOpera7 = fOperaVersion >= 7;
isMinOpera7_5 = fOperaVersion >= 7.5;
}
var isKHTML = ("KHTML") > -1 || ("Konqueror") > -1 || ("AppleWebKit") > -1;
var isMinSafari1 = isMinSafari1_2 = false;
var isMinKonq2_2 = isMinKonq3 = isMinKonq3_1 = isMinKonq3_2 = false;
if (isKHTML) {
var isSafari = ("AppleWebKit") > -1;
var isKonq = ("Konqueror") > -1;
if (isSafari) {
var reAppleWebKit = new RegExp("AppleWebKit\\/(\\d+(?:\\.\\d*)?)");
(sUserAgent);
var fAppleWebKitVersion = parseFloat(RegExp["$1"]);
isMinSafari1 = fAppleWebKitVersion >= 85;
isMinSafari1_2 = fAppleWebKitVersion >= 124;
}
else if (isKonq) {
var reKonq = new RegExp("Konqueror\\/(\\d+(?:\\.\\d+(?:\\.\\d)?)?)");
(sUserAgent);
isMinKonq2_2 = compareVersions(RegExp["$1"], "2.2") >= 0;
isMinKonq3 = compareVersions(RegExp["$1"], "3.0") >= 0;
isMinKonq3_1 = compareVersions(RegExp["$1"], "3.1") >= 0;
isMinKonq3_2 = compareVersions(RegExp["$1"], "3.2") >= 0;
}
}
var isIE = ("compatible") > -1 && ("MSIE") > -1 && !isOpera;
var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = isMinIE7 = false;
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
(sUserAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
isMinIE4 = fIEVersion >= 4;
isMinIE5 = fIEVersion >= 5;
isMinIE5_5 = fIEVersion >= 5.5;
isMinIE6 = fIEVersion >= 6.0;
isMinIE7 = fIEVersion >= 7.0;
}
var isMoz = ("Gecko") > -1 && !isKHTML;
var isMinMoz1 = sMinMoz1_4 = isMinMoz1_5 = false;
if (isMoz) {
var reMoz = new RegExp("rv:(\\d+\\.\\d+(?:\\.\\d+)?)");
(sUserAgent);
isMinMoz1 = compareVersions(RegExp["$1"], "1.0") >= 0;
isMinMoz1_4 = compareVersions(RegExp["$1"], "1.4") >= 0;
isMinMoz1_5 = compareVersions(RegExp["$1"], "1.5") >= 0;
}
var isNS4 = !isIE && !isOpera && !isMoz && !isKHTML
&& (("Mozilla") == 0)
&& ( == "Netscape")
&& (fAppVersion >= 4.0 && fAppVersion < 5.0);
var isMinNS4 = isMinNS4_5 = isMinNS4_7 = isMinNS4_8 = false;
if (isNS4) {
isMinNS4 = true;
isMinNS4_5 = fAppVersion >= 4.5;
isMinNS4_7 = fAppVersion >= 4.7;
isMinNS4_8 = fAppVersion >= 4.8;
}
var isWin = ( == "Win32") || ( == "Windows");
var isMac = ( == "Mac68K") || ( == "MacPPC")
|| ( == "Macintosh");
var isUnix = ( == "X11") && !isWin && !isMac;
var isWin95 = isWin98 = isWinNT4 = isWin2K = isWinME = isWinXP = false;
var isMac68K = isMacPPC = false;
var isSunOS = isMinSunOS4 = isMinSunOS5 = isMinSunOS5_5 = false;
if (isWin) {
isWin95 = ("Win95") > -1
|| ("Windows 95") > -1;
isWin98 = ("Win98") > -1
|| ("Windows 98") > -1;
isWinME = ("Win 9x 4.90") > -1
|| ("Windows ME") > -1;
isWin2K = ("Windows NT 5.0") > -1
|| ("Windows 2000") > -1;
isWinXP = ("Windows NT 5.1") > -1
|| ("Windows XP") > -1;
isWinNT4 = ("WinNT") > -1
|| ("Windows NT") > -1
|| ("WinNT4.0") > -1
|| ("Windows NT 4.0") > -1
&& (!isWinME && !isWin2K && !isWinXP);
}
if (isMac) {
isMac68K = ("Mac_68000") > -1
|| ("68K") > -1;
isMacPPC = ("Mac_PowerPC") > -1
|| ("PPC") > -1;
}
if (isUnix) {
isSunOS = ("SunOS") > -1;
if (isSunOS) {
var reSunOS = new RegExp("SunOS (\\d+\\.\\d+(?:\\.\\d+)?)");
(sUserAgent);
isMinSunOS4 = compareVersions(RegExp["$1"], "4.0") >= 0;
isMinSunOS5 = compareVersions(RegExp["$1"], "5.0") >= 0;
isMinSunOS5_5 = compareVersions(RegExp["$1"], "5.5") >= 0;
}
}
』
『
<html xmlns="http:///1999/xhtml" onclick="alert('html')">
<head>
<title>Unt title page</title>
<script type="text/javascript" language="javascript" src="javascript/"></script> //src="javascript/" To determine the type of the browser, there is ~
<script type="text/javascript" language="javascript">
function handleClick(oEvent) //Stop bubbles
{
alert("input");
if(isIE) {
=true; //E's method to prevent bubbles
}
else
{
(); //Other browsers' ways to prevent bubbles
}
}
</script>
</head>
<body onclick="alert('body')">
<input type="button" value="Click Me" onclick="handleClick(event)" /> // Trigger the onclick event to pop up three boxes because the button is included in them
</body>
</html>
』
JS Chapter 6: Form and Form Elements ↑↓←→
//Get the Form object
Copy the codeThe code is as follows:
The first method:
[0] refers to the first form in the document
The second method:
By the name of the form ["formZ"];
The third method:
(“forml”)
example
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script type="text/javascript" language="javascript">
function myclick1() {
var form;
form = ["samplename"]; //Three ways to get Form objects
// form = [0];
// form = ("myForm");
alert(["mytext"].value); //Output text: Marssion //["mytext"].value is used to obtain the value of an element in the form Note: "" is used in []
}
</script>
</head>
<body>
<form name="samplename" action="" method="post"> //method (the method of submitting the form (indicates whether the browser sends a Get request or a Post request)) [code] 1. Get: Unsafe, it is to follow the information to the URL, with a maximum of 255 characters
↑ 2. Post: The method used when submitting the form is safe, and the length of the characters placed is unlimited.
Form handler pointing to the server (a URL address, address to which the form is submitted) Special usage: <!--action="javascript:alert('Submitted')"-->
<input type="text" value="Marssion" name="mytext"/>
↑
Default value in text box
<input type="button" value="Click Me" onclick="myclick1()"/>
↑
Text on the button
</form>
</body>
</html>
[/code]
//Form form submission
Copy the codeThe code is as follows:
Previous Methods
<input type="submit" value="submit button submission"/>
Submit and reset with javascript
Submit() and reset() methods
<input type="button" value="Normal button submission" onclick="[0].submit()"/>
//onsubmit and onreset events
Copy the codeThe code is as follows:
The Form object also provides event handlers onsubmit and onreset
If false is returned, the form submission and reset will be cancelled. Note: Only when the Submit button is actually clicked will the onsubmit event handler be triggered (use "type="submit"")
Example onsubmit
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function check() {
var txtName = ("txtName");
var txtPwd = ("txtPassword");
if ( == "") {
alert("Please enter username");
();
return false;
}
if ( == "") {
alert("Please enter your password");
();
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="" onsubmit="return check()"> <!-- Note: Write onsubmit="return function name()"--> in form
<label for="txtName">Name:</label><br />
<input type="text" name="txtName" /><br />
<label for="txtPassword">Password:</label><br />
<input type="password" name="txtPassword" /><br />
<label for="selAge">Age:</label><br />
<select name="selAge" >
<option>18-21</option>
<option>22-25</option>
<option>26-29</option>
<option>30-35</option>
<option>Over 35</option>
</select><br />
<label for="txtComments">Comments:</label><br />
<textarea rows="10" cols="50" name="txtComments"></textarea><br />
<input type="submit" value="submit button submit"/> <!--submit button will trigger the onsubmit event-->
<input type="button" value="normal button submission" onclick="[0].submit()" /> <!--Ordinary buttons can be submitted successfully, but cannot trigger the onsubmit event-->
</form>
<p>This example blocks the form submissiong(you won't see an alert box).</p>
</body>
</html>
Example onreset
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
</head>
<body>
<form method="post" action="javascript:alert('Submitted')" onreset="return confirm('Really erase All data and start over?')">
<p>Type some values into the textboxes and then press reset.</p>
<label for="txtName">Name:</label><br />
<input type="text" name="txtName" /><br />
<label for="txtPassword">Password</label><br />
<input type="password" name="txtPassword" /><br />
<label for="selAge">Age:</label><br />
<select name="selAge" >
<option>18-21</option>
<option>22-25</option>
<option>26-29</option>
<option>30-35</option>
<option>Over 35</option>
</select><br />
<label for="txtComments">Comments:</label><br />
<textarea rows="10" cols="50" name="txtComments"></textarea><br />
<input type="submit" value="Submit Form" />
<input type="reset" value="reset button" /> <!-- Unlike onsubmit, whether it is "type="reset" reset button" or "onclick="[0].reset()" can successfully call the onreset event-->
<input type="button" value="normal button" onclick="[0].reset()" />
</form>
</body>
</html>
//Please submit the form once
Copy the codeThe code is as follows:
Solution: Use the general button and add the following events:
<input type=”button” value=”Submit”
onclick=”=true; ()” />
example
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function sub(){
setTimeout("sub1()",3000); <!-- The two functions written in <script></script> simulate the delayed submission when the network speed is slow- ->
}
function sub1(){
[0].submit();
}
</script>
</head>
<body>
<form method="post" action="../" name="form1">
<input type="text" name="txtName" value="" />
<input type="button" value="Submit Form" name="mySubmit1" onclick="=true;sub();" />
</form>
</body>
</html>
//The name of form and form elements
Copy the codeThe code is as follows:
You can use the following expression to refer to the "zipcode" element in the form of "address". Both the form and the element must use the name attribute.
Much more concise than using hardcoded (position dependency) array subscripts:
[1].elements[4]
example
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript">
function showTextBoxValue() {
//debugger
alert([0].elements[1].value);
alert(); //What is printed is the value filled in the text box. Note! : The following document is the name of the element!, and it cannot be clicked, so you can only force it
}
</script>
</head>
<body>
<form method="post" action="#" name="myForm">
<input type="text" name="txt" />
<input type="button" value="ShowValue" onclick="showTextBoxValue()" />
</form>
</body>
</html>
//Usual methods and properties of form elements
Copy the codeThe code is as follows:
Type: A read-only string that identifies the type of the form element.
Form: a read-only reference to the form object containing the element // is an element B =A of form A
Name: A read-only string specified by the name nature of HTML.
Value: A readable and writeable string that specifies the "value" contained or represented by the form element.
Methods: blur() and focus()
Example (blur)
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
</head>
<body>
<p>Type a few characters in the textbox and then tab to the Submit button.
Then,click on the textbox and tab back to the Submit button without changing the text.
</p>
<form method="post" action="javascript:alert('Submited')"> <!--Action that occurs when the submit button is pressed-->
<input type="text" name="textbox" value="" onblur="alert('Blur')" onchange="alert('Change')" /> <!--Onblur event occurs when the focus is lost The content in the text box changes when the focus is lost-->
<input type="submit" value="Submit Form" />
</form>
</body>
</html>
//Common form elements support event handlers
Copy the codeThe code is as follows:
Onclick: Triggered when the user clicks the mouse on the element.
Onchange: Triggered when the user changes the value represented by the element (by entering text or selecting an option).
Onfocus: The input focus is triggered when the form element is received
Onblur: Triggered when form element loses input focus
//Text box object
Copy the codeThe code is as follows:
event:
{
onBlur text box loses focus
The value of the onChange text box is modified (the event will track the changes made by the user in the text box, and the event will be activated after the user completes the modification in the text box.)
onFocus cursor enters text box
}
method:
{
select( ) Select the text content to highlight the input area (select the text content to highlight the input area, which is generally used to prompt the user to re-enter. (Select all, just like when entering the username on QQ, you can select all the contents in the text box with a double click, and delete them all at once))
}
property:
{
value represents the text entered by the user.
Size Specifies the visible length of the text
Maxlength specifies the maximum length that can be entered
readonly Some text boxes are expected to be unchanged by the user. For example, the starting price of an auction website is generally priced by the seller or auction company, so I hope that the user cannot modify it. At this time, you can specify the readonly read-only attribute.
}
Example (text box object onChange event)
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function getLength()
{
var oTextbox1=("txt1");
var oTextbox2=("txt2");
alert("The length of txt1 is " + + "\n" //Attribute is to obtain the length of the text in the text box
+"The length of txt2 is "+);
}
function change(){
("loading").src="img/loading_32x32.gif"; //Specify the path of the image
("loading"). = "block"; //="block" means to make the picture appear
}
function f(){
("loading").src="img/"; //Change
}
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<td><input type="text" size="12" onchange="change();" /></td> <!--When the user clicks elsewhere and the focus leaves this text box, the onchange event will be triggered-->
<td><img width="17" height="17" style="display:none" alt="" /></td> <!--style="display:none" means to hide the picture-->
</tr>
</table>
<textarea rows="5" cols="25" onkeypress="f()"></textarea><br /> <!--onkeypress event is when the user types a value in a multi-line text box and triggers this event -->
<input type="button" value="Get Length" onclick="getLength()" />
</body>
</html>
Example (text properties of text boxes, (dynamic addition of child nodes))
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function getValues()
{
var oTextbox1=("txt1");
var oTextbox2=("txt2");
var resultDiv=("result");
var childNode=(""); //Create an empty text node
=+;
if(==0) //If the number of child nodes of the layer (parent node) is equal to 0
{
(childNode);
}
else
{
([0]); //If the number of child nodes in the layer (parent node) is not equal to 0, first delete the first child node and add a new child node
(childNode);
}
}
</script>
</head>
<body>
<input type="text" size="12" /><br />
<textarea rows="5" cols="25" ></textarea>
<input type="button" value="Get Values" onclick="getValues()" /><br />
<div ></div>
</body>
</html>
Example (select method)
Copy the codeThe code is as follows:
<html xmlns="http:///1999/xhtml">
<head>
<title>Unt title page</title>
<script language="javascript" type="text/javascript">
function selectText()
{
var oTextbox1=("txt1");
(); //select() method: select all the contents in the corresponding text box
}
</script>
</head>
<body>
<input type="text" size="12" value="initial value" onselect="alert('Selected')" /><br /> <!--onselect event: Occurs when the user selects text (regardless of how long it is selected)-->
<input type="button" value="Select Text" onclick="selectText()" />
</body>
</html>
//Putdown list box (List Boxes and Combo Boxes)
Copy the codeThe code is as follows:
property:
The value attribute represents the value currently selected by the control.
The size attribute indicates the number of items that can be displayed.
options collection
Previous page123Next pageRead the full text