码迷,mamicode.com
首页 > 编程语言 > 详细

comp.lang.javascript FAQ [zz]

时间:2014-08-26 19:26:56      阅读:671      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   os   java   io   for   ar   

comp.lang.javascript FAQ

Version 32.2, Updated 2010-10-08, by Garrett Smith

1 Meta-FAQ meta-questions

This is the comp.lang.javascript meta-FAQ, 32.2. The latest version is available at http://jibbering.com/faq/ in HTML form.

Each day, one section of the FAQ is posted for review and questions, and as a reminder that the FAQ is available.

For additional explanation and detail relating to some aspects of the FAQ, please see the FAQ Notes. It has been provided separately to avoid increasing the size of the FAQ to a point where it would be unreasonable to post it to the group.

Code examples in this FAQ use JSDoc Toolkit comments.

1.1 Which newsgroups deal with javascript?

The official Big 8 Usenet newsgroup dealing with javascript is comp.lang.javascript. Some "language" hierarchies also have *.comp.lang.javascript groups.

c.l.js is an unmoderated newsgroup.

1.2 What questions are on-topic for comp.lang.javascript?

The comp.lang.javascript newsgroup deals with ECMAScript languages, so any questions about JavaScript or JScript are welcome. However, the majority of questions sent to this group relates to javascript in a web browser. If you are experiencing issues with a particular browser, or the host is not a browser at all, please make this information clear.

Javascript and Java are two completely different languages. Java questions should be asked in one of the comp.lang.java.* newsgroups; they are not appropriate for c.l.js (as Java and javascript are distinct programming languages with only superficial similarities due to sharing a C-like syntax and some of the characters in their names).

Questions dealing with other scripting languages, such as VBScript, PerlScript or CGI scripting are also off-topic, as are HTML-only or CSS-only questions.

Questions that are specific to Microsoft‘s JScript may also be appropriately asked at: microsoft.public.scripting.jscript

The comp.lang.javascript newsgroup charter is included in faq_notes/cljs_charter.html.

1.3 What should I do before posting to comp.lang.javascript?

Before posting to c.l.js, you should read this document. You should also check the Resources section.

How to Ask a Question

Replying

  • Quote only relevant parts of earlier messages, and add your comments below each quoted section (FYI28/RFC1855).
  • Link to specific sections of the FAQ that are relevant.
  • Avoid being unnecessarily rude, but do not complain about other rude posts.
  • Don‘t quote signatures.

Posting Code

  • Remove everything that does not contribute to the problem (images, markup, other scripts, etc).
  • Validate the HTML and CSS http://validator.w3.org/http://jigsaw.w3.org/css-validator/.
  • Make sure the code is executable as transmitted.
  • Format lines to 72 characters; indent with 2-4 spaces (not tabs).
  • State what you expect the code to do.
  • Mention the platforms, browsers, and versions.
  • See also the FAQ section on debugging.
  • Post in plain-text only. Do not encode it. Do not attach files.
  • If the code is more than about 100 lines, provide a URL in addition.
  • Do not multi-post; cross-post if necessary (Wikipedia description).

What Not to Post

  • Do not post job postings. Job postings should go to an appropriate regional jobs group.
  • Do not post copyright material without permission from the copyright holder.

Relevant announcements are welcome, but no more often than once per major release, as a short link to the product‘s webpage.

1.4 Why was my post not answered?

This could be for several reasons:

  • It was a variation of a frequently asked question and was therefore ignored by everyone.
  • Nobody knows the answer.
  • The person with the answer has not seen the post.
  • It might not be possible to do what you want to do but perhaps readers of c.l.js are reluctant to answer your post in the negative when they are not convinced that it cannot be done.
  • The question was not asked clearly enough, or did not included enough information to be answered.
  • The questioner did not realise the need to read the group, for a few days, to see the answers posted there.
  • You ignored the section on posting

If it is not one of these, then after a few days consider reposting after checking http://groups.google.com/group/comp.lang.javascript/topics for replies. Make sure the post is phrased well, and everything needed to answer is correct, and the subject is appropriate.

2 Language Overview

2.1 What is ECMAScript?

ECMA-262 is the international standard that current language implementations (JavaScript™, JScript etc.) are based on.

ECMA-262 defines the language Syntax, Types, Keywords, Operators, and built-in objects. The ECMAScript specification is the reference to determine the expected behavior of a program. ECMAScript does not define any host objects, such as documentwindow, or ActiveXObject.

ECMA-327 defines the Compact Profile of ECMAScript by describing the features from ECMA 262 that may be omitted in some resource-constrained environments.http://www.ecma-international.org/publications/standards/Ecma-327.htm

The most widely supported edition of ECMA-262 is the 3rd edition (1999). There is fair support for this edition in JScript 5.5+ (buggy) and good support JavaScript 1.5.

The term "javascript" is used as a common name for all dialects of ECMAScript.

2.2 What is JScript?

JScript is Microsoft‘s implementation of ECMAScript.

Questions that are specific to Microsoft‘s JScript may also be appropriately asked at: microsoft.public.scripting.jscript.

2.3 What is the Document Object Model (DOM)?

The Document Object Model (DOM) is a interface-based model for Document objects. The DOM allows scripts to dynamically access and update a document‘s content, style, and event handlers.

The DOM is not part of the ECMAScript programming language.

Official DOM standards are defined by the World Wide Web Consortium. Scriptable browsers also have proprietary DOM features (MSDNMDC), such as document.writeln().

Also see the section on DOM and Forms.

2.4 Internationalisation and Localisation in javascript

Internationalisation means using one form which is everywhere both acceptable and understood. Any international standard not supported by default can be coded for.

For example, there is an International Standard for numeric Gregorian date format; but none for decimal and thousands separators.

Localisation is the process of adapting software for a specific region or language by adding locale-specific components and translating text. It cannot work well in general, because it requires a knowledge of all preferences and the ability to choose the right one, in an environment where many systems are inappropriately set anyway.

ECMAScript has a few localisation features. The various toString() methods are all implementation dependent, but tend to use either UK or US settings (not necessarily correctly). ECMAScript Ed. 3 introduced some capabilities, including the toLocaleString()method which should create a string based on the host‘s locale.

ECMAScript 5th Edition introduces limited ISO 8601 capabilities with Date.prototype.toISOString() and new behavior for Date.parse().

2.5 What does the future hold for ECMAScript?

The 5th edition of ECMAScript was approved on 2009-12-04. There is some support in implementations released before approval date (JScript 5.8, JavaScript 1.8, JavaScriptCore). http://www.ecma-international.org/publications/standards/Ecma-262.htm

3 Javascript Resources

3.1 What books are recommended for javascript?

Most javascript books have been found to contain so many technical errors that consensus recommendations have not emerged from the group.

The following books have been considered to have value by some individuals on c.l.js. The reviews of these books are provided:

3.2 What online resources are available?

ECMAScript

The Official ECMAScript Specification
[ECMA-262] http://www.ecma-international.org/publications/standards/Ecma-262-arch.htm
[ISO16262] ISO/IEC 16262, Second Edition 2002-06-01 : ISO Standard matching ECMA-262 3rd Edition, with corrections.
http://standards.iso.org/ittf/PubliclyAvailableStandards/c033835_ISO_IEC_16262_2002(E).zip
[MS-ES3]: Internet Explorer ECMA-262 ECMAScript Language Specification Standards Support
http://msdn.microsoft.com/en-us/library/ff520996%28VS.85%29.aspx
res/%5BMS-ES3%5D.pdf (local alias)
[MS-ES3EX]: Microsoft JScript Extensions to the ECMAScript Language Specification Third Edition
http://msdn.microsoft.com/en-us/library/ff521046%28VS.85%29.aspx
res/%5BMS-ES3EX%5D.pdf (local alias)
ECMAScript on Wikipedia
http://en.wikipedia.org/wiki/ECMAScript

W3C DOM

DOM Level 1 ECMAScript Binding
http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
DOM Level 2 ECMAScript Binding
http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
DOM Level 2 Events
http://www.w3.org/TR/DOM-Level-2-Events/events.html
DOM Level 2 Style
http://www.w3.org/TR/DOM-Level-2-Style/
DOM Level 3 ECMAScript Binding
http://www.w3.org/TR/DOM-Level-3-Core/ecma-script-binding.html

Browser Documentation

Mozilla
JavaScript: http://developer.mozilla.org/en/docs/JavaScript
Gecko DOM Reference: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference
Microsoft
HTML and DHTML Reference: http://msdn.microsoft.com/en-us/library/ms533050.aspx
JScript Language Reference: http://msdn.microsoft.com/en-us/library/hbxc2t98%28VS.85%29.aspx
Scripting: http://msdn.microsoft.com/en-us/library/ms950396.aspx
Opera
Web Specifications Support: http://www.opera.com/docs/specs/#ecmascript
JavaScript Support: http://www.opera.com/docs/specs/js/
ECMAScript Support: http://www.opera.com/docs/specs/js/ecma
BlackBerry JavaScript Reference
http://docs.blackberry.com/en/developers/deliverables/11849/
ICab InScript
http://www.muchsoft.com/inscript/
Apple Safari
Web Content Guide: http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/Introduction/Introduction.html
Webkit
Project Site: http://webkit.org/
Wiki: http://trac.webkit.org/wiki
DOM Reference: http://developer.apple.com/Mac/library/documentation/AppleApplications/Reference/WebKitDOMRef/index.html#//apple_ref/doc/uid/TP40006089
Netscape 4 Client-Side JavaScript Reference
http://docs.sun.com/source/816-6408-10/
Archived documentation for MSIE 3.x
http://members.tripod.com/%7Ehousten/download/

Standalone ECMAScript Implementations

Rhino: An open-source implementation of JavaScript written in Java
http://www.mozilla.org/rhino/
Besen IDE: ECMAScript Edition 5 with IDE
http://besen.sourceforge.net/
V8: Google‘s open source JavaScript engine
http://code.google.com/p/v8/
SpiderMonkey: Mozilla‘s C implementation of JavaScript
http://www.mozilla.org/js/spidermonkey/
Digital Mars DMD Script, console and MS Active Script implementation of ECMAScript
http://www.digitalmars.com/dscript/

Other ECMAScript Implementations

Developing Dashboard Widgets: Apple Developer Connection
http://developer.apple.com/macosx/dashboard.html
Whitebeam Apache Module: Server Side JavaScript in Apache
http://www.whitebeam.org/

3.3 Javascript Libraries

No javascript libraries are endorsed by this group. If you want help with using a library, visit that library‘s discussion group instead.

4 Functions

4.1 What is (function(){ /*...*/ })() ?

This is an anonymous FunctionExpression that is called immediately after creation.

Variables declared inside a function are not accessible from outside the function. This can be useful, for example, to hide implementation details or to avoid polluting the global scope.

4.2 What is a function statement?

The term function statement has been widely and wrongly used to describe a FunctionDeclaration. This is misleading because in ECMAScript, a FunctionDeclaration is not aStatement; there are places in a program where a Statement is permitted but a FunctionDeclaration is not. To add to this confusion, some implementations, notably Mozillas‘, provide a syntax extension called function statement. This is allowed under section 16 of ECMA-262, Editions 3 and 5.

Example of nonstandard function statement:

// Nonstandard syntax, found in GMail source code. DO NOT USE.
try {
  // FunctionDeclaration not allowed in Block.
  function Fze(b,a){return b.unselectable=a}
  /*...*/
} catch(e) { _DumpException(e) }

Code that uses function statement has three known interpretations. Some implementations process Fze as a Statement, in order. Others, including JScript, evaluate Fzeupon entering the execution context that it appears in. Yet others, notably DMDScript and default configuration of BESEN, throw a SyntaxError.

For consistent behavior across implementations, do not use function statement; use either FunctionExpression or FunctionDeclaration instead.

Example of FunctionExpression (valid):

var Fze;
try {
  Fze = function(b,a){return b.unselectable=a};
  /*...*/
} catch(e) { _DumpException(e) }

Example of FunctionDeclaration (valid):

// Program code
function aa(b,a){return b.unselectable=a}

 

5 Dates

ISO 8601 defines date and time formats. Some benefits include:

  • language-independent and unambiguous world-wide
  • sortable with a trivial string comparison
  • easily readable and writable by software
  • compatible with standards ISO 9075 and rfc 3339

The ISO Extended format for common date is YYYY-MM-DD, and for time is hh:mm:ss.

For an event with an offset from UTC, use YYYY-MM-DDThh:mm:ss±hh:mm.

Never use a local date/time format for a non-local event. Instead, use UTC, as in YYYY-MM-DDThh:mm:ssZ (Z is the only letter suffix).

The T can be omitted where that would not cause ambiguity. For rfc 3339 compliance, it may be replaced by a space and for SQL, it must be replaced by a single space.

Year 0000 is unrecognized by some formats (XML Schema, xs:date).

5.1 How do I format a Date object with javascript?

A local Date object where 0 <= year <= 9999 can be formatted to a common ISO 8601 format YYYY-MM-DD with:-

  /** Formats a Date to YYYY-MM-DD (local time), compatible with both 
   *  ISO 8601 and ISO/IEC 9075-2:2003 (E) (SQL ‘date‘ type).
   *  @param {Date} dateInRange year 0000 to 9999.
   *  @throws {RangeError} if the year is not in range
   */
  function formatDate(dateInRange) {
     var year = dateInRange.getFullYear(),
         isInRange = year >= 0 && year <= 9999, yyyy, mm, dd;
     if(!isInRange) {
       throw RangeError("formatDate: year must be 0000-9999");
     }
     yyyy = ("000" + year).slice(-4);
     mm = ("0" + (dateInRange.getMonth() + 1)).slice(-2);
     dd = ("0" + (dateInRange.getDate())).slice(-2);
     return yyyy + "-" + mm + "-" + dd;
  }
  

5.2 How can I create a Date object from a String?

An Extended ISO 8601 local Date format YYYY-MM-DD can be parsed to a Date with the following:-

  /**Parses string formatted as YYYY-MM-DD to a Date object.
   * If the supplied string does not match the format, an 
   * invalid Date (value NaN) is returned.
   * @param {string} dateStringInRange format YYYY-MM-DD, with year in
   * range of 0000-9999, inclusive.
   * @return {Date} Date object representing the string.
   */
  function parseISO8601(dateStringInRange) {
    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);

    if(parts) {
      month = +parts[2];
      date.setFullYear(parts[1], month - 1, parts[3]);
      if(month != date.getMonth() + 1) {
        date.setTime(NaN);
      }
    }
    return date;
  }

6 Numbers

6.1 How do I format a Number as a String with exactly 2 decimal places?

When formatting money for example, to format 6.57634 to 6.58, 6.7 to 6.50, and 6 to 6.00?

Rounding of x.xx5 is unreliable, as most numbers are not represented exactly. See also: Why does simple decimal arithmetic give strange results?

The statement n = Math.round(n * 100)/100 converts n to a Number value close to a multiple of 0.01. However, there are some problems. Converting the number to a string (n + ""), does not give trailing zeroes. Rounding numbers that are very close to x.5, for example, Math.round(0.49999999999999992) results 1.

ECMA-262 3rd Edition introduced Number.prototype.toFixed. There are bugs in JScript 5.8 and below with certain numbers, for example 0.007.toFixed(2) incorrectly results 0.00.

 

var numberToFixed = 
(function() {
  return toFixedString;
  
  function toFixedString(n, digits) {
    var unsigned = toUnsignedString(Math.abs(n), digits);
    return (n < 0 ? "-" : "") + unsigned;
  }
  
  function toUnsignedString(m, digits) {
    var t, s = Math.round(m * Math.pow(10, digits)) + "",
        start, end;
    if (/\D/.test(s)) { 
      return "" + m;
    }
    s = padLeft(s, 1 + digits, "0");
    start = s.substring(0, t = (s.length - digits));
    end = s.substring(t);
    if(end) {
      end = "." + end;
    }
    return start + end; // avoid "0."
  }
  /** 
   * @param {string} input: input value converted to string.
   * @param {number} size: desired length of output.
   * @param {string} ch: single character to prefix to s.
   */
  function padLeft(input, size, ch) {
    var s = input + "";
    while(s.length < size) {
      s = ch + s;
    }
    return s;
  }
})();

// Test results 
document.writeln([
  "numberToFixed(9e-3, 12) => " + numberToFixed(9e-3, 12),
  "numberToFixed(1.255, 2) => " + numberToFixed(1.255, 2),
  "numberToFixed(1.355, 2) => " + numberToFixed(1.355, 2),
  "numberToFixed(0.1255, 3) => " + numberToFixed(0.1255, 3),
  "numberToFixed(0.07, 2)   => " + numberToFixed(0.07, 2),
  "numberToFixed(0.0000000006, 1) => " + numberToFixed(0.0000000006, 1),
  "numberToFixed(0.0000000006, 0) => " + numberToFixed(0.0000000006, 0)
].join("\n"));

6.2 Why does simple decimal arithmetic give strange results?

For example, 5 * 1.015 does not give exactly 5.075 and 0.06+0.01 does not give exactly 0.07 in javascript.

ECMAScript numbers are represented in binary as IEEE-754 (IEC 559) Doubles, with a resolution of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to just over 9e15 are precise, but few decimal fractions are. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.

In particular, non-integer results should not normally be compared for equality; and non-integer computed results commonly need rounding; see How do I format a Number as a String with exactly 2 decimal places?

Otherwise, use Math.round on the results of expressions which should be of integer value.

6.3 Why does K = parseInt(‘09‘) set K to 0?

Method parseInt generally needs a second parameter, radix, for the base (from 2 to 36).

If radix is omitted, the base is determined by the contents of the string. Any string beginning with ‘0x‘ or ‘0X‘ represents a hexadecimal number. A string beginning with a leading 0 may be parsed as octal (as if raxix were 8), in ECMA-262 Ed 3 (octal digits are 0-7). If string ‘09‘ is converted to 0.

To force use of a particular base, use the radix parameter: parseInt("09", base).

 

6.4 Why does 1+1 equal 11? or How do I convert a string to a number?

Variables are not typed; their values are. The conversion between a string and a number happens automatically.

The addition operator (+) performs concatenation if either operand is a string, thus "1" + 1 results "11". To perform addition, you might need to first convert the string to a number. For example +varname or Number(varname) or parseInt(varname, 10) or parseFloat(varname). Form control values are strings, as is the result from a promptdialog. Convert these to numbers before performing addition: +‘1‘ + 1 results 2.

6.5 How do I generate a random integer from 1 to n?

Math.random() returns a value R such that 0 <= R < 1.0; therefore:

  // positive integer expected
  function getRandomNumber(n) { 
    return Math.floor(n * Math.random());
  }

- gives an evenly distributed random integer in the range from 0 to n - 1 inclusive; use getRandomNumber(n)+1 for 1 to n.

7 Objects

7.1 What is a native object?

native object is any object whose semantics are fully defined by ECMA-262.

Some native objects are built-in; others, such as user-defined objects, may be constructed during the execution of an ECMAScript program.

Example:

// Native built-in objects:
var m = Math, // Built-in Math object.
    slice = Array.prototype.slice, // Built-in native method.
    o = {}, // Native user-defined object.
    f = function(){}, // Native user-defined function.
    d = new Date(),
    a = [],
    e = new Error("My Message.");
    

See also:

7.2 What is a built-in object?

built-in object is any object supplied by an ECMAScript implementation, independent of the host environment, that is present at the start of the execution of an ECMAScript program.

ECMA-262 3rd Edition defines the following built-in objects:

Objects
global, Math
Constructors
Object, Function, Array, String, Boolean, Number, Date, RegExp
Errors
Error, Date, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
Functions
eval, parseInt, parseFloat, isNaN, isFinite, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent

ECMA-262 Edition 5 defines also the built-in object JSON.

Nonstandard built-in objects may include RuntimeObjectString.prototype.linkCollectGarbage, and more.

7.3 What is a host object?

host object is any object supplied by the host environment to complete the execution environment of ECMAScript.

host object is not part of the ECMAScript implementation, but is exposed to the ECMAScript implementation.

host object may be implemented as a native ECMAScript object, however this is not required. For example, Internet Explorer implements many scriptable DOM objects as ActiveX Objects, often resulting in unexpected errors.

Availability and behavior of a host object depends on the host environment.

For example, in a browser, XMLHttpRequest might be available, with or without standard or proprietary features or events. Windows Script Host object model has the WScriptobject available.

For information on a particular host object, consult the pertinent documentation available for the implementation(s). For web browsers, this usually includes the w3c specifications as well as documentation for that browser. See also:

7.4 When should I use eval?

The eval function should only be used when it is necessary to evaluate a string supplied or composed at run-time; the string can be anything from a simple (but unpredictable) expression such as "12 * 2.54" to a substantial piece of javascript code.

When eval( ‘{"key" : 42}‘ ) is called, { is interpreted as a block of code instead of an object literal. Hence, the Grouping Operator (parentheses) is used to force eval to interpret the JSON as an object literal: eval( ‘({"key" : 42})‘ );.

7.5 How do I access a property of an object using a string?

There are two ways to access properties: dot notation and square bracket notation. What you are looking for is the square bracket notation in which the dot, and the identifier to its right, are replaced with a set of square brackets containing a string. The value of the string matches the identifier. For example:-

  //dot notation
  var bodyElement = document.body;

  //square bracket notation, using an expression
  var bodyElement = document["bo"+"dy"];

8 Strings and RegExp

8.1 How do I trim whitespace?

ECMAScript 5 defines String.prototype.trim. Where not supported, it can be added as a function that uses a regular expression:

if(!String.prototype.trim) {
  String.prototype.trim = function() {
    return String(this).replace(/^\s+|\s+$/g, "");
  };
} 

Implementations are inconsistent with \s. For example, some implementations, notably JScript 5.8 and Safari 2, do not match \xA0 (no-break space), among others.

A more consistent approach would be to create a character class that defines the characters to trim.

 

9 DOM and Forms

9.1 How do I get the value of a form control?

In HTML documents, a form may be referred to as a property of the document.forms collection, either by its ordinal index or by name (if the form has a name). A form‘s controls may be similarly referenced from its elements collection:

  var frm = document.forms[0];
  var control = frm.elements["elementname"];

Once a reference to a control is obtained, its (string) value property can be read:-

  var value = control.value;
  value = +control.value; //string to number.

Some exceptions would be:

First Exception: Where the control is a SELECT element, and support for older browsers, such as NN4, is required:

  var value = control.options[control.selectedIndex].value;

Second Exception: Where several controls share the same name, such as radio buttons. These are made available as collections and require additional handling. For more information, see:-

Third Exception: File inputs. Most current browsers do not allow reading of type="file" input elements in a way that is useful.

9.2 My element is named myselect[], how do I access it?

Form controls with any "illegal" characters can be accessed with formref.elements["myselect[]"] - The bracket characters, amongst others, are illegal in ID attributes and javascript identifiers, so you should try to avoid them as browsers may handle them incorrectly.

9.3 Why doesn‘t the global variable "divId" always refer to the element with id="divId"?

Microsoft introduced a shortcut that can be used to reference elements which include an id attribute where the id becomes a globally-accessible property. Some browsers reproduce this behavior. Some, most notably Gecko-based browsers (Netscape and Mozilla), do so only in "quirks" mode. The best approach is the document.getElementByIdmethod, which is part of the W3C DOM standard and implemented in modern browsers (including IE from version 5.0). So an element with id="foo" can be referenced with:-

  var el = document.getElementById("foo");

Note: make sure not to use the same id twice in the same document and do not give an element a name that matches an id of another in the same document or it will trigger bugs in MSIE <= 7 with document.getElementsByName and document.getElementById.

9.4 How do I modify the content of the current page?

Using the non-standard but widely implemented innerHTML property: <div id="anID">Some Content</div> with script:

  document.getElementById("anID").innerHTML = 
    "Some <em>new</em> Content";

Where "anID" is the (unique on the HTML page) id attribute value of the element to modify.

All versions of Internet Explorer exhibit problems with innerHTML, including:

  • Fails with FRAMESET, HEAD, HTML, STYLE, SELECT, OBJECT, and all TABLE-related elements.
  • Replaces consecutive whitespace characters with a single space.
  • Changes attribute values and order of appearance.
  • Removes quotations around attribute values.

If the new content is only text and does not need to replace existing HTML, it is more efficient to modify the data property of a text node.

  document.getElementById("anID").firstChild.data = "Some new Text";

Compatibility Note: Implementations have been known to split long text content among several adjacent text nodes, so replacing the data of the first text node may not replace all the element‘s text. The normalize method, where supported, will combine adjacent text nodes.

Note: Make sure the element exists in the document (has been parsed) before trying to reference it.

9.5 Why does my code fail to access an element?

An element can only be accessed after it exists in the document.

Either: A) include your script after the HTML element it refers to, or B) use the "load" event to trigger your script.

Example A:

<div id="snurgle">here</div>
<script type="text/javascript">
// Don‘t forget var.
var snurgleEl = document.getElementById("snurgle");
window.alert(snurgleEl.parentNode);
</script>

Example B:

// In the HEAD.
<script type="text/javascript">
window.onload = function(){
  var snurgleEl = document.getElementById("snurgle");
};
</script>

Other problems can include:

  • invalid HTML
  • two elements with the same name or id
  • use of an unsafe name: http://jibbering.com/names/

9.6 How can I see in javascript if a web browser accepts cookies?

Write a cookie and read it back and check if it‘s the same.

10 Windows and Frames

The window object (also referred to by self) is "DOM Level 0". No formal standard for it exists.

10.1 How can I disable the back button in a web browser?

You can‘t. The browser‘s history cannot be modified. However, you can use self.location.replace(url); in some browsers to replace the current page in the history.

10.2 How do I access a frame‘s content?

To reference another frame on the same domain:

The content window of a FRAME or IFRAME can be accessed by the frames collection.

Example:

var fwin;
fwin = self.frames[0]; // or:
fwin = self.frames["iframeName"];

or, from the IFRAME or FRAME element:

var iframeEl = document.getElementById("myFrame");
var fwin = iframeEl.contentWindow; // Nonstandard, but widely supported.
var fdoc = iframeEl.contentDocument; // DOM2 HTML Standard.

A global identifier moomin in the the iframe‘s content window is accessed as fwin.moomin.

To communicate between frames on different domains:

Where supported, (IE8, Firefox 3, Opera 9, Safari 4), use window.postMessage( message[, port], otherDomain);.

Example: http://jibbering.com/faq/example/postMessage.html

Where window.postMessage is not supported, the window.name property can be set on the other window, which can poll for updates to that property using setInterval(checkWinName, 100); where checkWinName is a function that polls to check the value of self.name.

10.3 How do I find the size of the window?

Here is a detailed explanation of a cross-browser strategy to find the dimensions of the viewport, excepting all chrome (excludes scrollbars, etc).

We can consider various properties:

  window.innerWidth
  document.clientWidth
  document.documentElement.clientWidth
  document.body.clientWidth

Of the browsers that have an innerWidth property, most include scrollbar dimensions. Some versions of KHTML browsers (including Safari 2) do not include scrollbar width.

The window.inner* properties are unreliable and not useful here. We don‘t want scrollbar dimensions included.

  document.clientWidth

Certain versions of KHTML, including Safari 2, have document.clientHeight and document.clientWidth properties. Where supported, these rare properties accurately return the height and width of the viewport, without including scrollbar dimensions.

  document.documentElement.clientWidth
  document.body.clientWidth

MSHTML (Trident), Firefox (Gecko), Opera (Presto), and Safari (Webkit) all support clientHeight on document.body and document.documentElement. The difficulty is figuring out which one is reliable. In other words which object to get the clientHeight property from:documentElement or body?

What the number returned from either of these properties represents depends on the environment. The environment includes the browser, its version, and the rendering mode of the document. In quirks mode, we‘ll mostly want to use body.clientHeight (except for in Safari 2).

  document.body.clientHeight

Some environments will return the viewport height. Others will return 0. Yet others will return the clientHeight of the BODY element.

  document.documentElement.clientHeight

This is the more "standard" property for getting the height of the viewport. It usually "works" in modern browsers in standards mode. Notable exceptions include Safari 2 and Opera <= 9.25, both of which return the clientHeight of the html element. (Oddly, Opera <= 9.25 in standards mode returns the width of the viewport fordocumentElement.clientWidth).

With the exception of Safari 2, body.clientHeight is reliable where documentElement.clientHeight is found to be unreliable. For example, in Safari 3+, Opera, and Mozilla, all in quirks mode, document.documentElement.clientHeight returns the clientHeight of the html element (this may seem unsurprising but it is not what we want).

Conversely, document.body.clientHeight will return the height of the viewport in most cases where document.documentElement.clientHeight does not. An exception to that is Safari 2, where documentElement.clientHeight and body.clientHeight both return the height of their corresponding element (not what we want).

By using a combination of Feature Testing and Capability Testing, the dimensions of the viewport can be strategically retrieved from the property that works in the environment the script is running in. The trick is determining which property will give us the value we want.

Since document.clientHeight is reliable where (rarely) supported, and since browsers that support this property don‘t return the viewport dimensions fromdocument.body.clientHeight or document.documentElement.clientHeight, this should be the very first condition:

  // Safari 2 uses document.clientWidth (default).
  if(typeof document.clientWidth == "number") {
     // use document.clientWidth.
  }

The next strategy is to determine if document.documentElement.clientHeight property is unreliable. It is deemed "unreliable" when it is either 0 or taller than the viewport.

Determining if documentElement.clientHeight is 0 is easy. The result is stored in a variable IS_BODY_ACTING_ROOT.

  var docEl = document.documentElement,
    IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
  docEl = null; 

To determine if documentElement.clientHeight returns a value taller than the viewport, we need a Capability Test.

If we can force documentElement to be very tall (taller than a normal viewport) we can then check to see if documentElement.clientHeight returns that "very tall" number. If it does, then it is unreliable.

We can force documentElement to be taller than the viewport (or any "normal" viewport) by adding a div to the body, give that div a height larger than any normal monitor, and then check to see if documentElement.clientHeight is that high (or "almost" that high, to account for documentElement having a border).

  // Used to feature test Opera returning wrong values 
  // for documentElement.clientHeight. 
  // The results of this function should be cached, 
  // so it does not need to be called more than once.
  function isDocumentElementHeightOff(){ 
      var d = document,
          div = d.createElement(‘div‘);
      div.style.height = "2500px";
      d.body.insertBefore(div, d.body.firstChild);
      var r = d.documentElement.clientHeight > 2400;
      d.body.removeChild(div);
      return r;
  }

We can use this function to see if we should use body.clientHeight, instead. (but only after checking if document.clientHeight is supported).

  // Safari 2 uses document.clientWidth (default).
  if(typeof document.clientWidth == "number") {
     // use document.clientHeight/Width.
  }
  else if(IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
      // use document.body.clientHeight/Width.
  } else {
      // use document.documentElement.clientHeight/Width.
  }

The preceding strategy was developed by Garrett Smith with input from John David Dalton. A complete and tested example can be found in APE Library underAPE.dom.getViewportDimensions. Source code: http://dhtmlkitchen.com/ape/build/dom/viewport-f.js. APE is publicly released under Academic Free License. APE home:http://dhtmlkitchen.com/ape/.

Note: The dimensions cannot be determined accurately until after the document has finished loading.

10.4 How do I check to see if a child window is open, before opening another?

 

  var myWin;
  function openWin(aURL) {
    if (!myWin || myWin.closed ) {
      myWin = window.open(aURL,‘myWin‘);
    } else {
      myWin.location.href = aURL;
      myWin.focus();
    }
  }

Popup windows cause usability problems and are generally best avoided.

10.5 Why does framename.print() not print the correct frame in IE?

IE prints the frame that has focus when you call the print method frameref.focus();frameref.print();

10.6 How do I close a window and why does it not work on the first one?

If a window was opened by javascript, then it can be closed without confirmation by using windowRef.close().

Before calling windowRef.close() (or other window methods), make sure the window reference is not null and its closed property is false.

Popup windows cause usability problems and are generally best avoided.

 

10.7 Why do I get permission denied when accessing a frame/window?

In the normal browser security model, a script may only access the properties of documents served from the same domain or IP address, protocol, and port.

Any attempt to access a property in such cases will result in a "Permission Denied" error. Signed scripts or trusted ActiveX objects can overcome this in limited situations.

10.8 How do I make a 10 second delay?

There is no built-in way to pause execution in javascript such as a sleep function, but hosts usually provide a method of some form. Web browsers are designed for event driven programming and only provide the setTimeout and setInterval functions to facilitate timed delays. The delay before calling getSnork may exceed the second parameter tosetTimeout and setInterval due to implementation differences among browsers.

To call the function getSnork, approximately 10 seconds after the function getMoomin() completes, you would do this:

  getMoomin();
  setTimeout(getSnork, 10000); 

Script execution is not stopped, and adding getSnufkin() after the setTimeout line would immediately execute the function getSnufkin before getSnork.

Achieving delays through running a loop of some sort for a pre-defined period is a bad strategy, as that will inhibit whatever was supposed to be happening during the delay, including blocking user interation.

Other (less event driven) hosts have different wait functions, such as WScript.Sleep() in the Windows Script Host.

10.9 How do I change print settings for window.print()?

In a normal security environment, you can‘t change anything.

Print Stylesheet rules provide options.

For IE, ActiveX or Plugin ScriptX and Neptune from Meadroid to give you more control for Windows versions of Internet Explorer, Netscape, and Opera.

10.10 How do I change the confirm box to say yes/no or default to cancel?

The buttons on a confirm box cannot be changed, nor can a default button be specified.

Change the question to a statement so that "OK" is suitable as the default response.

Example: "Would you like us to charge your credit card?" (wrong) "We will now charge your credit card." (right).

10.11 How do I prompt a "Save As" dialog for an accepted mime type?

It is not possible with client-side javascript.

Some browsers accept the Content-Disposition header, but this must be added by the server. Taking the form:- Content-Disposition: attachment; filename=filename.ext

10.12 How do I modify the current browser window?

In a default security environment you are very limited in how much you can modify the current browser window. You can use window.resizeTo or window.moveTo to resize or move a window respectively, but that is it. Normally you can only suggest chrome changes in a window.open.

10.13 How do I POST a form to a new window?

Use the target attribute on the form, opening a window with that name and your feature string in the onsubmit handler of the FORM.

  <form action="" method="post"
      target="wndname" onsubmit="window.open(‘‘,this.target);return true;">

10.14 How do I open a new window with javascript?

New windows can be opened on browsers that support the window.open function and are not subject to the action of any pop-up blocking mechanism with code such as:-

  var wRef;
  if(window.open){
    wRef = window.open("http://example.com/page.html","windowName");
  }

11 Ajax and Server Communication

11.1 What is Ajax?

Ajax is shorthand for Asynchronous JavaScript and XML. The technology is based on the XMLHttpRequest Object. At its simplest, it is the sending/retrieving of new data from the server without changing or reloading the window location.

11.2 How do I download a page to a variable?

Although XMLHttpRequest can be used to download entire pages, it is often used for downloading small pieces of data that can be used to update the current page.

11.3 How do I get a jsp/php variable into client-side javascript?

Use a server-side language to generate the javascript.

Certain characters of ECMAScript strings must be escaped by backslash. These include quote marks, backslash, and line terminators.

JSP Example, using Apache Commons: org.apache.commons.lang.StringEscapeUtils:

var jsVar = "<%= StringEscapeUtils.escapeJavaScript(str) %>";

PHP example using addcslashes:

var jsVar = "<?php echo addcslashes($str,"\\\‘\"\n\r"); ?>";

11.4 How do I log-out a user when they leave my site?

This cannot be done reliably. Here‘s why:

  • The user may disable javascript so the log-out script will never execute.
  • The user may not be on-line when they close your web page.
  • Javascript errors elsewhere in the page may prevent the script executing.
  • The browser may not support the onunload event, or may not fire it under certain circumstances, so the log-out function will not execute.

The URL below has more information.

11.5 How do I run a server side script?

You trigger a server-side script by sending an HTTP request. This can be achieved by setting the src of an imgImageframe, or iframe, or by using XHR, where supported.

An image will also "swallow" the data sent back by the server, so that they will not be visible anywhere.

 

  var dummyImage = new Image();
  dummyImage.src = "scriptURL.asp?param=" + varName;

Mozilla, Opera 7.6+, Safari 1.2+, and Windows IE 7 provide the XMLHttpRequest object (Windows IE versions 5+, provides ActiveX to acheive an analagous effect).XMLHttpRequest can send HTTP requests to the server, and provides access the responseText or responseXML (when the response is XML), and HTTP header information.

11.6 How do I force a reload from the server/prevent caching?

To reload a page, use location.reload(). However, this depends upon the cache headers that your server sends. To change this, you need to alter the server configuration. A quick fix on the client is to change the page URI so that it contains a unique element, such as the current time. For example: location.replace(location.href+‘?d=‘+new Date().valueOf()) If the location.href already contains a query String, use: location.replace(location.href+‘&d=‘+new Date().valueOf())

11.7 Why is my Ajax page not updated properly when using an HTTP GET request in Internet Explorer?

Browsers cache the results of HTTP requests to reduce network traffic. To force the browser to request the document from the server, either set the EXPIRES and/or CACHE-CONTROL response header(s) with a past date or use a unique query string.

  req.open("GET", "/example.jsp?date=" + (+new Date), true); 

Always use the appropriate HTTP method. Do not use POST to prevent caching. See RFC 2616.

12 Debugging

12.1 How do I get my browser to report javascript errors?

There are debugging tools for many browsers. Learn to use them all.

Windows
Fiddler. Fiddler is an HTTP Debugging proxy (it won‘t find script errors). Fiddler logs HTTP activity, like Firebug‘s Net tab, but can be attached to any browser running on Windows.
Windows IE
Microsoft Script Editor. Included with Visual Studio or Microsoft Word 2003 (discontinued in Office 2007). To enable, ToolsInternet OptionsAdvanced, and uncheckDisable Script Debugging. After enabling Script Debugging, a Script Debugger option will appear in the View menu.
IETester for testing IE 5.5- IE8.
CompanionJSconsole for IE.
Note: For debugging scripts in IE, the Microsoft Script Editor is recommended. However, if not available, the Microsoft Script Debugger may be somewhat helpful.
Internet Explorer Developer Toolbar
To report errors: Wait until a little yellow triangle appears at the left end of the status bar, double click on it and, when the error dialog box appears, check the "Always show errors" checkbox it contains. Or, Internet OptionsAdvanced, deselect "Disable Script Debugging", select "Display a notification ...".
Firefox
Tools > Error console (Ctrl + Shift + j).
Firebug
YSlow. YSlow analyzes web pages and tells you why they‘re slow based on Yahoo‘s rules for high performance web sites.
Lori Lori or Life-of-request info, is useful for troubleshooting server response and page load time.
Web Developer Toolbar.
Cookie Watcher.
XPather. XPath generator, editor and inspector.
Opera
Tools > Advanced > Error console
Introduction to Opera Dragonfly
Safari
To display the Develop menu in Safari 3.1 or higher, select the checkbox labeled "Show Develop menu in menu bar" in Safari‘s Advanced Preferences panel.
Safari Web Inspector
Chrome
JavaScript Console: click the Page menu icon and select Developer > JavaScript Console. From here, you‘ll be able to view errors in the JavaScript execution, and enter additional javascript commands to execute.
JavaScript Debugger: available as Page menu icon > Developer > Debug JavaScript, the debugger provides a command prompt from which you can set breakpoints, backtrace, and more. Type help at the debugger command line to get started.
Mac IE
Use the Preferences dialog.

13 Things not to attempt in a browser

13.1 How do I detect Opera/Safari/IE?

The short answer: Don‘t do that.

The navigator host object contains properties which may identify the browser and version. These properties are historically inaccurate. Some browsers allow the user to set navigator.userAgent to any value. For example, Firefox, (type about:config and search useragent or Safari, Develop > User Agent > Other..., IE, via Registry.

Other browsers, such as Opera, provide a list of user agents for the user to select from. There are also at least 25 other javascript capable browsers, with multiple versions, each with their own string.

Browser detection is unreliable, at best. It usually causes forward-compatibility and maintenance problems. It is unrelated to the problem or incompatiblity it is trying to solve and obscures the problems it is used for, where it is used.

Object detection is checking that the object in question exists. Capability detection goes one step further to actually test the object, method, or property, to see if behaves in the desired manner.

Feature Test Example:

/** 
 * Returns the element/object the user targeted.
 * If neither DOM nor IE event model is supported, returns undefined. 
 * @throws TypeError if the event is not an object.
 */
function getEventTarget(e) {
  e = e || window.event;
  // First check for the existence of standard "target" property.
  return e.target || e.srcElement;
}

13.2 How can I prevent access to a web page by using javascript?

In practice you can‘t. While you could create a suitable encryption system with a password in the page, the level of support you need to do this means it‘s always simpler to do it server-side. Anything that "protects" a page other than the current one is definitely flawed.

13.3 How do I protect my javascript code?

With clientside javascript you can‘t as your code is distributed in source form and is easily readable. With JScript, there is the Script Encoder (see MSDN), but this is nothing more than obfuscation. Attempting to disable the context menu does nothing to protect your script in a Web browser.

13.4 How do I suppress a context menu (right-click menu)?

A context menu, often triggered by right-click, can be requested by the user in a few ways. For example, on windows, shift + F10 and on macs, click-and-hold. Other input devices exist and mouse buttons can be configured, making the term "right click" a misnomer, in context.

In browsers that allow it, a script can suppress the context menu by returning false from an object‘s oncontextmenu event handler.

document.oncontextmenu = function() {
  return false;
};

Some browsers lack context menus (e.g. iphone). Browsers that have context menus do not always have a scriptable event for them. Some browsers can be configured to disallow scripts from detecting context menu events (IE, Opera); others may fire the event but be configured to disallow scripts from suppressing the context menu (Firefox,Seamonkey).

Even when the context menu has been suppressed, it will still be possible to view/save the source code and to save images.

13.5 How can I access the client-side filesystem?

Security means that by default you can‘t. In a more restricted environment, there are options. For example, using LiveConnect to connect to Java with Netscape, and using the FileSystemObject in IE. Check Google Groups archives for previous posts on the subject.

13.6 I have <a href="javascript:somefunction()"> what ... ?

Whatever the rest of your question, this is generally a very bad idea. The javascript: pseudo protocol was designed to replace the current document with the value that is returned from the expression. For example:

  <a href="javascript:‘&lt;h1&gt;‘ + document.lastModified + ‘&lt;/h1&gt;‘">lastModified</a>

will result in replacing the current document with the value returned from document.lastModified, wrapped in an <h1> tag.

When the expression used evaluates to an undefined value (as some function calls do), the contents of the current page are not replaced. Regardless, some browsers (notably IE6) interpret this as navigation and will enter into a ‘navigation‘ state where GIF animations and plugins (such as movies) will stop and navigational features such as META refresh, assignment to location.href, and image swaps fail.

It is also possible for IE to be configured such that it supports javascript but not the javascript: protocol. This results in the user seeing a protocol error forjavascript: URIs.

The javascript: pseudo protocol creates accessibility and usability problems. It provides no fallback for when the script is not supported.

Instead, use <a href="something.html" onclick="somefunction();return false"> where something.html is a meaningful alternative. Alternatively, attach the click callback using an event registry.

14 Comments and Suggestions

The FAQ uses the stylesheet faq.css and is generated from the xml source index.xml by the windows script host script process.wsf which also checks the links.

14.1 Why do some posts have <FAQENTRY> in them?

If a poster feels that the question they are answering should be covered in the FAQ, placing <FAQENTRY> in the post lets the FAQ robot collect the messages for easy review and inclusion. A Draft Proposal for the FAQ is requested and appreciated.

The <FAQENTRY> should not be used in posts except in conjunction with a suggestion/proposal for the FAQ. It should also not be literally quoted in replies, instead it should be partly obscured as, e.g. <FAQ**TRY> or similar.

14.2 How do I make a suggestion?

The FAQ is currently lacking a maintainer, please contact Jim Ley (jim.ley@gmail.com) if you wish to take it over, you will need to be in good standing in the group and trustworthy to have access to the server. All comments, suggestions, and especially corrections are welcome.

comp.lang.javascript FAQ [zz]

标签:des   style   blog   http   os   java   io   for   ar   

原文地址:http://www.cnblogs.com/catkin2009/p/3937725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!