js

最後更新: 2015-05-24

目錄

 

介紹

Based on an open standard called ECMAScript(JavaScript, JScript and ActionScript.)

- conjunction with HTML and CSS
- add interactivity to web pages


Example

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Hello World</title>
        <!-- CSS for presentation. -->
        <style>
            h1 { font-size: 14px; color: hotpink; }
            button { color: red; }
        </style>
    </head>
    <body>
        <h1>Hello World</h1>
        <button>Click Me!</button>
        <!-- JavaScript for interactivity. -->
        <script>
            // Get a handle on the first button element in the document.
            var button = document.querySelector( "button" );
            // If a user clicks on it, say hello!
            button.addEventListener( "click", function( ev ) {
                alert( "Hello" );
            }, false);
        </script>
    </body>
</html>

External 與 Inline

-  External # <script src="/path/to/example.js"></script>
-  Inline   # <script> alert( "Hello World!" ); </script>

defer

i.e.

<script src="dist/js/bootstrap-checkbox.min.js" defer></script>

defer attribute

* The defer attribute is only for external scripts

Truly deferring javascript means loading or parsing of that javascript only begins after page content has loaded

If async is present:

    The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

If async is not present and defer is present:

    The script is executed when the page has finished parsing

If neither async or defer is present:

    The script is fetched and executed immediately, before the browser continues parsing the page

 

Placement

if the code will interact with the elements on the page,
you have to make sure those elements exist at the time the script is executed.

import, include, or require

JavaScript has no import, include, or require. There are other ways for JavaScript to include external JavaScript contents, though.

Call the function written in one JS file in another JS file

<head>
....
    <script src="File2.js" type="text/javascript"></script>
    <script src="File1.js" type="text/javascript"></script>
....
<head>
<body>
...
    <script type="text/javascript">
       alertOne();
    </script>
...
</body>

Syntax

Comment

 - //

 - /* */

Types

    String          ( escape characters "\" )
    Number
    Boolean
    null              ( absence of a value )
    undefined

 


Usage

 

// Define a null value

var foo = null;

// Two ways to achieve an undefined value

var bar1 = undefined;
var bar2;

javascript variable name 唔可以有 "hyphen" !

所以

background-color

要寫成

settings['background-color']

// strict equality operator

var x;
x === undefined; // true

var foo = 1;
var baz = "1";

foo == baz;              // true;
foo === baz;             // false

not

!=
!==    # not equal value or not equal type

// String + Number

foo + Number(baz)

 


Objects

 

// Using an empty object literal
var person1 = {};
// Assign properties using "dot notation"
person1.firstName = "John";
person1.lastName = "Doe";
// Access properties using "dot notation"
alert( person1.firstName + " " + person1.lastName );

// Creating an object with the object literal syntax:
var person2 = {
    firstName: "Jane",
    lastName: "Doe"
};

// Assign properties using "bracket notation"
// As mentioned, objects can also have objects as a property value
var people = {};
people[ "person1" ] = person1;
people[ "person2" ] = person2;
// Access properties using a mix of both bracket and dot notation
alert( people[ "person1" ].firstName );
alert( people[ "person2" ].firstName );

---------------

var myObject = {
    sayHello: function() {
        console.log( "hello" );
    },
        myName: "Rebecca"
};
myObject.sayHello(); // "hello"

---------------

var myObject = {
    validIdentifier: 123,
    "some string": 456,
    99999: 789
};

for ( var prop in myObject ) {
    // Determine if the property is on the object itself.
    // (not on the prototype)
    if ( myObject.hasOwnProperty( prop ) ) {
        console.log( "Property : " + prop + " ; value : " + myObject[ prop ] );
    }
}

# "this" Keyword

// A function invoked using Function.call()
var myObject = {
    sayHello: function() {
    console.log( "Hi! My name is " + this.myName );
    },
    myName: "Rebecca"
};
var secondObject = {
    myName: "Colin"
};

myObject.sayHello(); // "Hi! My name is Rebecca"
myObject.sayHello.call( secondObject ); // "Hi! My name is Colin"

// A function created using Function.bind()
var myName = "the global object";
var sayHello = function() {
    console.log( "Hi! My name is " + this.myName );
};
var myObject = {
    myName: "Rebecca"
};

sayHello(); // "Hi! My name is the global object"

var myObjectHello = sayHello.bind( myObject );
myObjectHello(); // "Hi! My name is Rebecca"

// A function being attached to an object at runtime.
var myName = "the global object";
var sayHello = function() {
    console.log( "Hi! My name is " + this.myName );
};

var myObject = {
    myName: "Rebecca"
};
var secondObject = {
    myName: "Colin"
};

myObject.sayHello = sayHello;
sayHello(); // "Hi! My name is the global object"
myObject.sayHello(); // "Hi! My name is Rebecca"

secondObject.sayHello = sayHello;
secondObject.sayHello(); // "Hi! My name is Colin"

# Array

var foo = new Array;
OR
var bar = [];

var foo = [ 100 ];
OR
var bar = new Array( 100 );

array methods:

push(), pop(),
unshift(), shift()
.length
.concat()
.sort()
.reverse()
.join()               // myArray.join( )  # default separator is a comma

.slice()
# Extracts a part of the array and returns that part in a new array.

var myArray = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
var newArray = myArray.slice( 3 );
console.log( myArray ); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
console.log( newArray ); // [ 4, 5, 6, 7, 8 ]

.splice()

var myArray = [ 0, 7, 8, 5 ];
myArray.splice( 1, 2, 1, 2, 3, 4 );
console.log( myArray ); // [ 0, 1, 2, 3, 4, 5 ]

.forEach()

    function printElementAndIndex( elem, index ) {
        console.log( "Index " + index + ": " + elem );
    }

    myArray = [ 1, 2, 3, 4, 5 ];

    myArray.forEach( printElementAndIndex );

# Checking

var myValue = [ 1, 2, 3 ];
// Using JavaScript's typeof operator to test for primitive types:
typeof myValue === "string"; // false
typeof myValue === "number"; // false
typeof myValue === "undefined"; // false
typeof myValue === "boolean"; // false

// Using jQuery's methods to check for non-primitive types:
jQuery.isFunction( myValue ); // false
jQuery.isPlainObject( myValue ); // false
jQuery.isArray( myValue ); // true
 


Debug

 

console.log( foo + +bar );

 


Flow Control

 

Conditional Code

if ( foo ) {
    // This code will run.
} else {
    // This code would run if foo and bar were both false.
}

Ternary Operator

var foo = bar ? 1 : 0;

Switch Statements

switch ( foo ) {
case "bar":
    alert( "the value was bar -- yay!" );
    break;
case "baz":
    alert( "boo baz :(" );
    break;
default:
    alert( "everything else is just ok" );
}

# Loops

for

for ( var i = 0; i < 5; i++ ) {
// Logs "try 0", "try 1", ..., "try 4".
console.log( "try " + i );
}

+for ( prop in obj ) {
    // statements here will be executed for every key in the object
    console.log( prop + ': ' + obj[ prop ] );
}

while

while ( [conditional] ) {
    [loopBody]
}

do

do {
    [loopBody]
} while ( [conditional] )

continue;
break;

 


Functions

var greet = function( person, greeting ) {
    var text = greeting + ", " + person;
    return text;
};

Immediately-Invoked Function

# no variables declared inside of the function are visible outside of it.

(function() {
    var foo = "Hello world";
})();

# Scope

* If you declare a variable and forget to use the "var" keyword,
* that variable is automatically made global.

function myFunc() {
    x = 5;
}
console.log( x ); // 5

* local scope works through functions (inner() can access outer(), But the outer() access inner())

function outer() {
    var x = 5;
    function inner() {
        console.log( x );
        var y = 10;
    }
    inner(); // 5
    console.log( y ); // ReferenceError: y is not defined
}

# Closures

# With closures, functions have access to variables that were available in the scope where the function was created.
# the function "sees" the change in the variable's value even after the function is defined,
# resulting in each function referencing the last value stored in the variable.

// Each function executed within the loop will reference
// the last value stored in i (5).
// This won't behave as we want it to - every 100 milliseconds, 5 will alert
for ( var i = 0; i < 5; i++ ) {
    setTimeout(function() {
        alert( i );
    }, i * 100 );
}

# Display an alert box after 3 seconds (3000 milliseconds):

setTimeout(function(){ alert("Hello"); }, 3000);

Closures version:

var createFunction = function( i ) {
    return function() {
        alert( i );
    };
};
for ( var i = 0; i < 5; i++ ) {
    setTimeout( createFunction( i ), i * 100 );
}

 


Timer

 

# setInterval

window.setInterval("javascript function", milliseconds);

// Alert "hello" every 3 seconds:
setInterval(function () {alert("Hello")}, 3000);

# Stop

myVar=setInterval("javascript function", milliseconds);

window.clearInterval(intervalVariable)

# setTimeout()

// Display an alert box after 3 seconds (3000 milliseconds)

myVar=setTimeout("javascript function", milliseconds);

window.clearTimeout(timeoutVariable)
 


Date()

 

var d = new Date();

Method

  • getFullYear()
  • getMonth()
  • getDate()
  • getHours()
  • getMinutes()
  • getSeconds()
  • getDay()
  • parse() "date string" -> "milliseconds "

Example

var t = new Date(ev.date.valueOf());
yyyy = t.getFullYear();
mm = t.getMonth() + 1;
dd = t.getDate();
var result = yyyy + "-" + mm + "-" + dd;
console.log(result);

 


xhr ajax - XMLHttpRequest Object

 

variable = new XMLHttpRequest();

 

# open(method, url, async)
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send()

 

function onRcvData () {
 if (ajax.readyState == 4) {
  if (ajax.status == 200) {
   var content = document.getElementById ('content');
   content.innerHTML = ajax.responseText;
  } else {
   alert ("伺服器處理錯誤");
  }
 }
}

 

1.readyState:
 0:尚未讀取
 1:讀取中
 2:已下載完畢
 3:資訊交換中
 4:處理完畢
2.Status:即HTTP協定的狀態碼
3.responseText:回應內容