|
获得对象
window.document.getElementById(“firstParagraph”)
Elements supporting the name attribute are predominantly
related to forms, images, and frames. You will see how name attributes work in forms in Chapter 9. In fact,
most browsers still require the name attribute for forms and form controls (text fields, buttons, and select lists)
for their data to be submitted to a server. It is permissible to assign the same identifier to both the id and name
attributes of an element.
访问对象的属性
<input type=”button” id=”clicker” name=”clicker” value=”Hit Me...”>
Therefore, for the button and text object
tags just shown, references to various properties are
document.getElementById(“clicker”).name
document.getElementById(“clicker”).value
document.getElementById(“entry”).value
访问对象的方法
An object can have any number of methods associated with it (including none at all). To set a method into
motion (usually called invoking a method), a JavaScript statement must include a reference to it, via its object
with a pair of parentheses after the method name, as in the following examples:
document.getElementById(“orderForm”).submit()
document.getElementById(“entry”).focus()
window.moveTo(50,100)
事件
<input type=”button” value=”Click Me” onclick=”window.alert (‘Ouch!’)”>
单引号和双引号同等
<script>标签
<script type=”text/javascript”>
one or more lines of JavaScript code here
</script>
<script type=”text/javascript” src=”myscript.js”></script>
Tag positions
Where do these tags go within a document? The answer is, anywhere they’re needed in the document. Most
of the time, it makes sense to include the tags nested within the <head>...</head> tag set; other times, it
is essential that you drop the script into a very specific location in the <body>...</body> section.
<script type=”text/javascript”>
<!--
//script statement(s) here
...
// -->
</script>
When Script Statements Execute
Now that you know where scripts go in a document, it’s time to look at when they run. Depending on what
you need a script to do, you have four choices for determining when a script runs:
While a document loads
Immediately after a document loads
In response to user action
When called upon by other script statements
The determining factor is how the script statements are positioned in a document.
While a document loads: immediate execution
<html>
<head>
<title>My First Script--II</title>
<style type=”text/css”>
.highlight {font-weight: bold}
</style>
</head>
<body>
<h1>Let’s Script...</h1>
<hr>
<script type=”text/javascript”>
<!-- hide from old browsers
document.write(“This browser is version “ + navigator.appVersion);
document.write(“ of <span class=’highlight’>” + navigator.appName + “</span>.”);
// end script hiding -->
</script>
</body>
</html>
Run after loading
<html>
<head>
<title>An onload script</title>
<script type=”text/javascript”>
<!--
function done() {
alert(“The page has finished loading.”);
}
// -->
</script>
</head>
<body onload=”done()”>
Here is some body text.
</body>
</html>
Run by user
<html>
<head>
<title>An onclick script</title>
<script type=”text/javascript”>
<!--
function alertUser() {
alert(“Ouch!”);
}
// -->
</script>
</head>
<body>
Here is some body text.
<form>
<input type=”text” name=”entry”>
<input type=”button” name=”oneButton” value=”Press Me!” onclick=”alertUser()”>
</form>
</body>
</html>
Called by another function
数据类型
JavaScript Value (Data) Types
Type Example Description
String A series of characters inside quote marks
“Howdy”
Number Any number not inside quote marks
4.5
Boolean A logical true or false
true
Null Devoid of any content but a value just the same
null
Object A software thing that is defined by its properties and
methods (arrays are also objects)
Function A function definition
定义变量
var myAge = 45;
A JavaScript variable can hold any value type. Unlike many other languages, you don’t have to tell
JavaScript during variable declaration what type of value the variable will hold. In fact, the value type of a
variable can change during the execution of a program. (This flexibility drives experienced programmers
crazy because they’re accustomed to assigning both a data type and a value to a variable.)
Converting strings to numbers
parseInt(“42”) // result = 42
parseInt(“42.33”) // result = 42
parseFloat(“42”) // result = 42
parseFloat(“42.33”) // result = 42.33
Converting numbers to strings
(“” + 2500) // result = “2500”
(“” + 2500).length // result = 4
Operators
firstName = “John”;
lastName = “Doe”;
fullName = firstName + “ “ + lastName;
JavaScript uses the same plus operator for arithmetic addition. When both operands are numbers, JavaScript
knows to treat the expression as an arithmetic addition rather than a string concatenation. The standard math
operators for addition, subtraction, multiplication, and division (+, -, *, /) are built into JavaScript.
JavaScript Comparison Operators
Symbol Description
Equals
==
Does not equal
!=
Is greater than
>
Is greater than or equal to
>=
Is less than
<
Is less than or equal to
<=
Control Structures
if (myAge < 18) {
alert(“Sorry, you cannot vote.”);
}
var febDays;
var theYear = 2004;
if (theYear % 4 == 0) {
febDays = 29;
} else {
febDays = 28;
}
for (var i = startValue; i <= maxValue; i++) {
statement[s] inside loop
}
Functions
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
Variable scope
Speaking of variables, it’s time to distinguish between variables that are defined outside and those that are
defined inside functions. Variables defined outside functions are called global variables; those defined inside
functions with the var keyword are called local variables.
A global variable has a slightly different connotation in JavaScript than it has in most other languages. For a
JavaScript script, the globe of a global variable is the current document loaded in a browser window or
frame. Therefore, when you initialize a variable as a global variable, it means that all script statements in the
page (including those inside functions) have direct access to that variable’s value via the variable’s name.
Statements can retrieve and modify global variables from anywhere in the page. In programming terminol-
ogy, this kind of variable is said to have global scope because every statement on the page can see it.
It is important to remember that the instant a page unloads itself, all global variables defined in that page
disappear from memory forever. If you need a value to persist from one page to another, you must use other
techniques to store that value (for example, as a global variable in a framesetting document, as described in
Chapter 16, or in a cookie, as described in Chapter 18). Although the var keyword is usually optional for
initializing global variables, I strongly recommend that you use it for all variable initializations to guard
against future changes to the JavaScript language.
<head>
<script type=”text/javascript”>
var aBoy = “Charlie Brown”; // global
var hisDog = “Snoopy”; // global
function demo() {
// using improper design to demonstrate a point
var hisDog = “Gromit”; // local version of hisDog
var output = hisDog + “ does not belong to “ + aBoy + “.<br>”;
document.write(output);
}
</script>
</head>
<body>
<script type=”text/javascript”>
demo(); // runs as document loads
document.write(hisDog + “ belongs to “ + aBoy + “.”);
</script>
</body>
数组
var USStates = new Array(51);
USStates[0] = “Alabama”;
To fill in the rest of the rows, I include a statement for each row:
USStates[1] = “Alaska”;
USStates[2] = “Arizona”;
USStates[3] = “Arkansas”;
...
USStates[50] = “Wyoming”
Document objects in arrays
document.getElementById(“entryForm”).elements.length
document.forms[0].elements.length
窗口对象
window.alert(“This is a JavaScript alert dialog.”);
if (confirm(“Are you sure you want to start over?”)) {
location.href = “index.html”;
}
var answer = prompt(“What is your name?”,””);
if (answer) {
alert(“Hello, “ + answer + “!”);
}
地址栏对象location Object
location.href = “http://www.dannyg.com”;
navigator Object
navigator.userAgent property
文档属性
[window.]document.propertyName
[window.]document.methodName([parameters])
document.forms[] property
It is convenient that the document object contains a property — document.forms — whose value is an
array of all form element objects in the document. As you recall from the discussion of arrays in Chapter 7,
an index number inside an array’s square brackets points to one of the elements in the array. To find out
how many form objects are in the current document, use
document.forms.length
document.forms[0]
document.forms[“formName”]
document.formName
document.images[] property
document.images array may be reached either by numeric or string index of the img element’s name.
Just as with forms, the name attribute value is the identifier you use for a string index.
document.write() method
<script type=”text/javascript”>
function reWrite() {
// assemble content for new window
var newContent = “<html><head><title>A New Doc</title></head>”;
newContent += “<body bgcolor=’aqua’><h1>This document is brand new.</h1>”;
newContent += “Click the Back button to see original document.”;
newContent += “</body></html>”;
// write HTML to new window document
document.write(newContent);
document.close(); // close layout stream
}
<script type=”text/javascript”>
var newWindow;
function makeNewWindow() {
newWindow = window.open(“”,””,”status,height=200,width=300”);
}
function subWrite() {
// make new window if someone has closed it
if (newWindow.closed) {
makeNewWindow();
}
// bring subwindow to front
newWindow.focus();
// assemble content for new window
var newContent = “<html><head><title>A New Doc</title></head>”;
newContent += “<body bgcolor=’coral’><h1>This document is brand new.</h1>”;
newContent += “</body></html>”;
// write HTML to new window document
newWindow.document.write(newContent);
newWindow.document.close(); // close layout stream
}
</script>
</head>
<body onload=”makeNewWindow()”>
<form>
<input type=”button” value=”Write to Subwindow” onclick=”subWrite()”>
</form>
document.createElement() and
document.createTextNode() methods
The document.createElement() method lets you create in the browser’s memory a brand-new element
object. To specify the precise element you wish to create, pass the tag name of the element as a string
parameter of the method:
var newElem = document.createElement(“p”);
You may also wish to add some attribute values to the element, which you may do by assigning values to
the newly created object’s properties, even before the element becomes part of the document.
As you saw in Chapter 4’s object hierarchy illustrations, an element object frequently needs text content
between its start and end tags. The W3C DOM way to create that text is to generate a brand-new text node
via the document.createTextNode() method and populate the node with the desired text. For example:
var newText = document.createTextNode(“Greetings to all.”);
document.getElementById() method
document.getElementById(“output”)
The method returns a value, which you typically preserve in a variable for use by subsequent script
statements:
var oneTable = document.getElementById(“salesResults”); |
|