2015年5月3日 星期日

JavaScript and HTML DOM Reference

The references describe the properties and methods of all JavaScript objects, along with examples.

String Number Operators Statements Math Date Array Boolean RegExp Global Conversion

Browser Objects Reference

The references describe the properties and methods of each object, along with examples.

Window Navigator Screen History Location

HTML DOM Reference

The references describe the properties and methods of the HTML DOM, along with examples.

HTML Document HTML Element HTML Attributes HTML Event

HTML Element Objects Reference

The references describe the properties and methods of each HTML object, along with examples.

a abbr address area article aside audio b base bdo blockquote body br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form head header hgroup h1 - h6 hr html i iframe img ins input button input checkbox input color input date input datetime input datetime-local input email input file input hidden input image input month input number input password input radio input range input reset input search input submit input text input time input url input week kbd keygen label legend li link map mark menu menuitem meta meter nav object ol optgroup option output p param pre progress q s samp script section select small source span strong style sub summary sup table td th tr textarea time title track u ul var video


詳細內容可以參考:

JavaScript Window - The Browser Object Model(BOM)

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.


The Browser Object Model (BOM)

There are no official standards for the Browser Object Model (BOM).
說白話一點,這其實是瀏覽器的標準,跟JS沒有關係,只是要理解JS怎麼跟Brower溝通。

Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.


The Window Object(瀏覽器物件)

The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document object (of the HTML DOM) is a property of the window object:
即使是DOM物件,其實也是BOM的子物件(或視為其一個功能屬性。

window.document.getElementById("header");
is the same as:
document.getElementById("header");

多數使用window的函數(功能/指令)時,window這個字通常被省略。


Window Size

Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).

A practical JavaScript solution (covering all browsers):
用或著來判斷使用者的版本,而用不同的指令語法

Example

var w = window.innerWidth
|| document.documentElement.clientWidth  //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientWidth;     //For 舊版IE 8, 7, 6, 5:語法
ar h = window.innerHeight
|| document.documentElement.clientHeight   //For 舊版IE 8, 7, 6, 5:語法
|| document.body.clientHeight;
  //For 舊版IE 8, 7, 6, 5:語法

The example displays the browser window's height and width: (NOT including toolbars/scrollbars)


Other Window Methods

Some other methods:

    • window.open() - open a new window
    • window.close() - close the current window
    • window.moveTo() -move the current window
    • window.resizeTo() -resize the current window

The window.screen object contains information about the user's screen.


Window Screen (螢幕物件)

The window.screen object can be written without the window prefix(t前輟Window可省)

Properties:

  • screen.width       
  • screen.height
  • screen.availWidth     //minus interface features like the Windows Taskbar
  • screen.availHeight     //minus interface features like the Windows Taskbar
  • screen.colorDepth
  • screen.pixelDepth

The screen.colorDepth property returns the number of bits used to display one color.

All modern computers use 24 bit or 32 bit hardware for color resolution:

  • 24 bits =      16,777,216 different "True Colors"
  • 32 bits = 4,294,967,296 different "Deep Colors"

Older computers used 16 bits: 65,536 different "High Colors" resulution.
Very old computers, and old cell phones used 8 bits: 256 different "VGA colors".

The #rrggbb (rgb) values used in HTML represents "True Colors" (16,777,216 different colors)

Window Screen Pixel Depth

The screen.pixelDepth property returns the pixel depth of the screen.

For modern computers, Color Depth and Pixel Depth are equal.


Window Location (伺服器當地物件)

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

The window.location object can be written without the window prefix.(前輟Window可省)

Some examples:

  • window.location.href            //returns the href (URL) of the current page
    Result is: http://www.w3schools.com/js/js_window_location.asp
  • window.location.hostname   //returns the domain name of the web host
    Result is: www.w3schools.com
  • window.location.pathname  //returns the path and filename of the current page
    Result is:/js/js_window_location.asp
  • window.location.protocol     //returns the web protocol used (http:// or https://)
    Result is:http:  (網頁使用的通訊協定)
  • window.location.assign()      //Method load a new document “ 載入新文件”


Window History (瀏覽器的歷史記錄物件)

The window.history object contains the browsers history.

The window.history object can be written without the window prefix.(前輟Window可省)

To protect the privacy of the users, there are limitations to how JavaScript can access this object.

methods:   //使用這個方法來做上一頁、下一頁的控制

  • history.back() - same as clicking back in the browser
  • history.forward() - same as clicking forward in the browser

History.Back()  and History.Forward()

The history.back()        method loads the previous URL in the history list.
The history forward()   method loads the next URL in the history list.

Example

Create a back button on a page:

<html>
<head>
<script>
function goBack() {
    window.history.back()
}

function goForward() {
    window.history.forward()

}

</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
<input type="button" value="Forward" onclick="goForward()">

</body>
</html>

The output of the code above will be:

The window.navigator object contains information about the visitor's browser.


Window Navigator (瀏覽器版本物件)

The window.navigator object can be written without the window prefix.(前輟Window可省)

Some examples:

  • navigator.appName              //Result is:Netscape
  • navigator.appCodeName       //Result is: Mozilla
  • navigator.cookieEnabled      //true能讀寫cookie;false否則關閉
  • navigator.product                //Result is:Gecko,瀏覽器的引擊版本
  • navigator.appVersion           //Result is:5.0 (Windows)
  • navigator.userAgent            
    //Result is:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
  • navigator.platform                //Result is: Win32
  • navigator.language              //Result is: zh-TW
  • navigator.javaEnabled()       //Result is: false 能否JAVA

Example

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " + navigator.appCodeName;
</script>

Try it Yourself »

Did you know?
IE11, Chrome, Firefox, and Safari return appName "Netscape".
Chrome, Firefox, IE, Safari, and Opera
all return appCodeName "Mozilla".

Warning !!!(嚴重警告)

The information from the navigator object can often be misleading(誤導), and should not be used to detect(檢測) browser versions because:
從Navigator物件得來資料是容易誤導的,不應該用這個方法來檢測瀏覽器的版本。原因如下:

  • Different browsers can use the same name
    //不同瀏覽器可能用相同的名稱
  • The navigator data can be changed by the browser owner
    //資料能被瀏覽器的使用者改變
  • Some browsers misidentify themselves to bypass site tests
    //有些瀏覽器失去視別而己能繞過網站的測試
  • Browsers cannot report new operating systems, released later than the browser
    //不能回報一個新的作業系統、新版本的瀏覽器

JavaScript has three kind of popup boxes: 三種對話框
Alert box, Confirm box, and Prompt box.

  • Alert();               //

  • Confirm();          //OK to return ture ; Cancel

  • Prompt();           //If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.


    Syntax
    window.prompt("sometext","defaultText");
    The window.prompt() method can be written without the window prefix.

Example

var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
    document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}

Try it Yourself »

Line Breaks 在文字框內用 \n 可以斷行
alert("Hello\nHow are you?");


JavaScript Timing Events 定時器事件

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds

Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.


The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function", milliseconds);       //(前輟Window可省)The first parameter of setInterval() should be a function.

The second parameter indicates the length of the time-intervals(間隔) between each execution.

Note: There are 1000 milliseconds in one second.

How to Stop the Execution? 停止執行

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

window.clearInterval(intervalVariable)                     //(前輟Window可省)

To be able to use the clearInterval() method, you must use a global variable when creating the interval method:

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

Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop time" button:

<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
var myVar = setInterval(function () {myTimer()}, 1000);
function myTimer() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

Try it Yourself »


The setTimeout() Method

Syntax

window.setTimeout("javascript function", milliseconds);       //(前輟Window可省)

The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

The first parameter of setTimeout() should be a function.

The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

How to Stop the Execution?

Syntax

window.clearTimeout(timeoutVariable)

To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:

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

Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.


What are Cookies?

Cookies let you store user information in web pages.

Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username=John Doe

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.


Create a Cookie with JavaScript (DOM物件)

JavaScript can create, read, and delete cookies with the document.cookie property.
With JavaScript, a cookie can be created like this:

document.cookie="username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Read a Cookie with JavaScript

With JavaScript, cookies can be read like this:

var x = document.cookie;

document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;

 

Change a Cookie with JavaScript

With JavaScript, you can change a cookie the same way as you create it:

document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";              //The old cookie is overwritten.

Delete a Cookie with JavaScript

Deleting a cookie is very simple. Just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Note that you don't have to specify a cookie value when you delete a cookie.

 

The Cookie String

The document.cookie property looks like a normal text string. But it is not.
Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is added to document.cookie, so if you read document.cookie again you will get something like:

cookie1=value; cookie2=value;

If you want to find the value of one specified cookie, you must write a JavaScript function that searches for the cookie value in the cookie string.

JavaScript Cookie Example

In the example to follow, we will create a cookie that stores the name of a visitor.

The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he will get a welcome message.

For the example we will create 3 JavaScript functions:

  1. A function to set a cookie value
  2. A function to get a cookie value
  3. A function to check a cookie value

A Function to Set a Cookie

First, we create a function that stores the name of the visitor in a cookie variable:

Example

function setCookie(cname, cvalue, exdays) {
var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

Example explained:

The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.


A Function to Get a Cookie

Then, we create a function that returns the value of a specified cookie:

Example

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
return "";
}

Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), and read out each value c=ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length,c.length).

If the cookie is not found, return "".


A Function to Check a Cookie

Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function:


All Together Now Example

function setCookie(cname, cvalue, exdays) {
var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}


function getCookie(cname) {           
  //a function to get a cookie
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
return "";
}


function checkCookie() {                   
//a function to check a cookie
var user = getCookie("username");
if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}

Try it Yourself »


詳細內容可以參考:

2015年4月29日 星期三

JavaScript HTML DOM Document

With the HTML DOM, the document object is your web page.


The HTML DOM Document

In the HTML DOM object model, the document object represents(代表/意味著是) your web page. The document object is the owner of all other objects in your web page. If you want to access objects in an HTML page, you always start with accessing the document object.


Finding HTML Elements(取得HTML的元素)

Method Description
document.getElementById() Find an element by element id
用ID代表:唯一
document.getElementsByTagName() Find elements by tag name
用標籤名稱代表,有多個同時選取。
document.getElementsByClassName() Find elements by class name
用群組/類名代表:好幾個元素。


Changing HTML Elements元素的屬性

Method Description
element.innerHTML= Change the inner HTML of an element
<tagName>
inner指的就這個區塊要放入的內容
</tagName>
element.attribute= Change the attribute of an HTML element
<tagName id=”ID名稱” > </tagName>
element.setAttribute(attribute,value) Change the attribute of an HTML element
<tagName id=”ID名稱” > </tagName>

設定A屬性,值Value
element.style.property= Change the style of an HTML element
樣式屬性值:
   

Adding and Deleting Elements 增/刪元素

document.createElement() Create an HTML element
document.removeChild() Remove an HTML element
document.appendChild() Add an HTML element
document.replaceChild()    Replace an HTML element
document.write(text)   Write into the HTML output stream
text幾乎等同整個<html></html>的內容。
因此不寫資料進去,就等於清空網頁的資料。


Adding Events Handlers
一個點擊事件語法,可說是標準/常用到不行的一個「寫法」

Method Description
document.getElementById(id).onclick=function() {
code
}
Adding event handler code to an onclick event
特色1:使用無名函數寫法
特色2:指定元素後直接使用其方法
而方法則對應一個無名函數。

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5. Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated棄用 in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete過時. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1

2015年4月19日 星期日

JavaScript Math Object

  • The Math object allows you to perform mathematical tasks.
  • The Math object includes several mathematical methods.

One common use of the Math object is to create a random number:

Math.random();         // returns a random number 點後.16位 

Math has no constructor. No methods have to create a Math object first.


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Math.min(0, 150, 30, 20, -8);        // returns –8
Math.max(0, 150, 30, 20, -8);       // returns 150


Math.round()    四捨五入取整數

Math.round() rounds a number to the nearest integer:

Math.round(4.7);            // returns 5
Math.round(4.4);            // returns 4


Math.ceil()        無條件UP取大整數

Math.ceil() rounds a number up to the nearest integer:

Math.ceil(4.4);             // returns  5
Math.ceil(-4.9);             // returns -4

 

Math.floor()       無條件down取小整數

Math.floor() rounds a number down to the nearest integer:

Math.floor(4.7);            // returns 4
Math.floor(-4.7);            // returns -5

 

Math.floor() and Math.random() can be used together to return a random number between 0 and 10:利用這個方法來得到一個0到10的整數

Math.floor(Math.random() * 11); 
// returns a random number between 0 and 10


Math Constants 八個常數值

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Math.E;                     // returns Euler's number
Math.PI                     // returns PI         圓周率
Math.SQRT2             // returns the square root of 2
Math.SQRT1_2          // returns the square root of 1/2
Math.LN2                  // returns the natural logarithm of 2
Math.LN10                // returns the natural logarithm of 10
Math.LOG2E             // returns base 2 logarithm of E
Math.LOG10E           // returns base 10 logarithm of E

Try it Yourself »


Math Object Methods(真正的數學函數!)

Method

Description

abs(x) Returns the absolute value of x                                       //絶對值
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x)

Returns x, rounded downwards to the nearest integer

log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y                      //次方
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x                                          //開根號
tan(x) Returns the tangent of an angle


Complete Math Reference

For a complete reference, go to our complete Math object reference.

The reference contains descriptions and examples of all Math properties and methods.

JavaScript Events事件

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.


HTML Events

An HTML event can be something the browser does, or something a user does.
網頁的事件一些由瀏覽器觸發,一些由使用者觸動。

Here are some examples of HTML events: (瀏覽器觸發)

  • An HTML web page has finished loading
    //完成下載
  • An HTML input field was changed
    //輸入字段被改變
  • An HTML button was clicked
    點擊按鈕

Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

  • With single quotes: <some-HTML-element some-event='some JavaScript'>
  • With double quotes:<some-HTML-element some-event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a button element:

<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>

In the example above, the JavaScript code changes the content of the element with id="demo".

In the next example, the code changes the content of it's own element (using this.innerHTML):

<button onclick="this.innerHTML=Date()">The time is?</button>

上面這兩個例子,把一推指令、參數、都寫在一起,利用單/雙引號來區別也是可以順利執行。但如再長就很容易出錯。因此通常看到下列的用法:
JavaScript code is often several lines long. It is more common to see event attributes calling functions:

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>


Common HTML Events

Here is a list of some common HTML events:

Event

Description

onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.


What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

  • Things that should be done every time a page loads
  • Things that should be done when the page is closed
  • Action that should be performed when a user clicks a button
  • Content that should be verified when a user inputs data
  • And more ...

Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can assign your own event handler functions to HTML elements
  • You can prevent events from being sent or being handled
  • And more ...


You will learn a lot more about events and event handlers in the HTML DOM chapters.


JavaScript Scope(變數的範圍)

Scope is the set of variables you have access to.


JavaScript Scope

In JavaScript, objects and functions, are also variables.

In JavaScript, scope is the set of variables, objects, and functions you have access to.

JavaScript has function scope: The scope changes inside functions.


Local JavaScript Variables(內部作用)

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have local scope: They can only be accessed within the function.

// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}

 

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.


Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it. 

var carName = " Volvo";
// code here can use carName
function myFunction() {
// code here can use carName
}


Automatically Global(自動全局要小心!!)

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare carName as a global variable, even if it is executed inside a function.

// code here can use carName
function myFunction() {
    carName = "Volvo";
// code here can use carName
}


The Lifetime of JavaScript Variables

  • The lifetime of a JavaScript variable starts when it is declared.
  • Local variables are deleted when the function is completed.
  • Global variables are deleted when you close the page.

Function Arguments

Function arguments (parameters) work as local variables inside functions.


Global Variables in HTML

With JavaScript, the global scope is the complete JavaScript environment.

In HTML, the global scope is the window object: All global variables belong to the window object.全域變數是視窗物件等級,所以就成了視窗的一個屬性

// code here can use window.carName
function myFunction() {
    carName = "Volvo";
}


Did You Know?
Your global variables, or functions, can overwrite window variables or functions.
Anyone, including the window object, can overwrite your global variables or functions.

草稿未完

以前偶爾也想多認識一下程式語言,只是沒這此久。那時費了大半時間還沒認識Function,一時熱情早就被一堆冷變數、資料型態、數學運算、邏輯判斷早就把人弄翻了!

其次,(早期)學習新東西總要用些舉來或實務來增加理解。大部份的例子並沒有錯或不好,但是例子的範圍無形的限制了我們初期生成的觀念,一不小心沒注意到就成了進階時的障礙!那麼來吧!我們也舉例一下囉!

早先例如:變數/變量的宣告及使用,我們可以說宣告一個變量就把一個很多櫃子的拿來使用,櫃子本身在物理條件下,就好像可以看成execl這的資料表的儲存格,真的也是如此的儲存格。所以格子的最外橫向可以做編號、縱向也可做編號,使用變數就像在這些空間的使用。像這樣的例子原則上沒錯吧!也沒什麼大問題。當然問題不在那,而是我們並沒有弄懂這些存儲格的環境。

(至少現在的看法)其實我覺得,運作範圍電腦的內在實務上運作是比較「大」,因而乎略中間過程,這樣反而告成學習的障礙。也就是把乎略的中間過程補回來,思維層級自然就會前進二層,相對的反而更好理解為麼這麼做而不那麼做!

也就是說電腦這小東西,它的運作構架反而可以大到等同一個國家或縣市級的運作程度,或許用最相似的加工區及物流倉儲來說,例如:這個地上有10棟大樓、每棟10樓、每樓10個線、每線100坪?為什麼最後用100坪而不用架子呢?其實是保留一點彈性。因為這是個萬能制造工廠,有些是生產制造區,有些是倉儲區。

因此不管你做什麼這個空間己是固定,這個環境就是電腦的總體資源,硬體上的編號通常是制式的。例如棟、樓及本身的占地面及空間。然啦!我們基本上還是會放上架子或櫃子而架子或櫃子又可放上些格子來分類。所以大體上就是如此!可是會什麼要這廢話多事呢?因為我們必需要明白,電腦運作中我們看不到的架構,這些都是OS的工作。

就如每個倉都使用同樣資料來表來紀錄存放管理資料,就如EXECL這樣的資料表,表中儲存格就可以很好識別、管理及對應到那放這10坪架上放的資料物件!但同樣的一張表如果換到鄰近的其它10坪或隔壁倉去,所對應到內容就會不一樣也不合用!

另一方面這些過程都透過管理中心的個別窗口來處理。所以同樣一個指令在每個位置的結果都是會不同。而現場也同有一組對應用窗口來服務。簡言之,我們下的每一個小小指令或動作,電腦處理都經過很複雜的對應關聯後,再簡化到我們看到。

例如:也我們會說,把左三的東西刪西,就完成了一動作。也沒說那棟、那層、那倉來做,那是因為對應窗口早已設在那相對的位置,所以不要那麼複雜。但如果指令有跨區就會有其它的互動問題,對應的層級不一樣,就有安全機制,這就是「作用域的觀念。」每個工作小組都有對外、對內、及內部管理的機制,就是要記住這件事就對。


物件不是物件?!

這裡順便引入物件這個東西,它不難,因為它是不是東西,基本上他是一個觀念、思法,一種思考的方式。有了它初期很痛苦,後期很強大。這些我想了好久,用我比較熟悉的領域,也許可以解釋。

我們常常用車子、房子來解釋物件是什麼,這很容易理解,但卻造成更多的障礙。為什麼是障礙呢?首先,物件就一個東西來看,有東西就有名稱。而物件本身通常又有很多物件組成,所以又可逐一的剖解好幾層的細部部件,這些還是物件。所以不同層級時,我們處理的內容也會有所不同。我想這樣的解釋都聽過N百遍了,然而依舊無法理理程序語言中的物件是什麼東西。

用個雙性這個特殊字眼也許較容理解它的特別,。

 

因為在寫程序並沒成品,更沒有物品,更該說是設計圖。就像室內設計一樣,在圖面上我們設定了很桌子、椅子、櫃子、燈、明這些物件及用什麼料質、顏色等屬性等等總設計概念圖,有了全局的架構,我們再個別局部去設計各室的空間及細節,也可設計部份元素的創新施工圖。然而些都只是一個前製而己。所以房子是物件、車子是物件、桌子是物件這些一樣也沒有出現。

物件導向我們一般是做單一小物件的細節規劃及製作流程,或是小組織的配置規劃。OP的視窗架構就是物件,而瀏覽器也是一個物件。

而Function用函數這個名稱,我是覺得很不好用,另一個「作用、功用、功能、方法」更能實現他的真正內涵。就是他是為了完成一個動作而設定。也就是連續做些事的的SOP。也就是SOP是不變的,沒有呼叫或調用它,他就不會有結果出來,然不管如何他都只是一個SOP。以物件導向來想就是物件的方法,方法依照SOP去完成一連串工作,最後會有一個結果或品。

2015年4月18日 星期六

Object物件、Function函數、Array矩陣


JavaScript Function Syntax

A Function is much the same as a Procedure or a Subroutine, in other programming languages.
在其他編程語言,函數是大致相同的程序或子程序。

function name(parameter1, parameter2, parameter3) {
code to be executed
}

name 在JS中,名稱可以省略。而形成無名函數用法。
( parameter1, parameter2, … ) (小括號) 就是運作執行{}中的代碼之意。從物件導向觀點,就是方法。
{ code to be executed           } {封閉代碼區塊}在所有語言,是一個獨立運作的範圍。而它於封閉區塊內的變數通常是獨立的。而要注意的是每個語言對其區塊的互動方式會有不同。
通常對外有的上層、同級、下層的主要互動關係。這個關係就是偏向物件模式。

return 語句代碼;           //個代碼運作結果就把(資料/值/內容)回傳。至於要傳回什麼內容由自己決定。如果沒設return,則代碼運行完就清空了。


Object Definition

//單行
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

//多行

var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
};

屬性名稱:語句代碼 ,
屬性名稱其實就是變數/常數的名稱,名稱就是"字串"。語句代碼(表達式)的結果就成為它的值。


Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array-name = [item1, item2, ...];      

Example:

var cars = ["Saab", "Volvo", "BMW"];

JS的陣列似乎是用來"快速"、"簡便"的存取一連串的資料而設計的,所以名稱的定義就省略。這是JS特色也是使用上要注意的。又它是物件,所以不就是一個表單物件嗎?

item這個值的內容,就直接當作是一個表達式、一個語句。

而用來讀取清單內容,就由0.1.2...依序來指定。  <==這個架構一般程式語言亦慣用

陣列名稱.length           //結果:計算item的個數  , (.)不就是物件的用法嗎?

所以處理陣列最常用的法式就用循環 for (起始,判斷,增減值)

陣列是一個物件,typeof 陳列;            //結果:是物件。
這就很明白的說明array物件的關係了嗎?


JavaScript Array Methods <==物件導向思維!

The strength of JavaScript arrays lies in the array methods.
(陣列最大的價值就是在其(方法)。
PHP也是如此重要

Converting Arrays to Strings
把內容值以文串寫出來

valueOf()、toString()、join(“連接字串”)  <==預設值[,] 
In JavaScript, all objects have the valueOf() and toString() methods.
JS中的所有物件都有valueOf()及toString()這兩個方法。
For JavaScript arrays, valueOf() and toString() are equal.
就數組而這兩個()方法是相等。

Popping碰!拍!掉最後一個 and Pushing從後推/塞入一個

pop()、push()
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.

 

Shifting Elements(移位)
shift() :前進一位,自然擠掉第一個值。
unshift( 結果值) :後退一位,最前補入結果值。

 

 

Deleting Elements(刪除某欄的值)
delete oneArrayName[ n ]     
刪除[n號欄位]值,仍保留欄位空間。但因為其欄位沒有值,因而資料類型屬"未定義"。

 

Splicing an Array(併接數組內容)

splice (從此欄,移出幾欄,再由此加 欄1值,欄2值,..)

Sorting an Array(排序內容)

sort()                         //正向排序
reverse()                  //反向排序

//內容排序有一定的規則,通常以"字串"型式ACSII的編號決定。所以當是數字值,就會出現不如預期的結果。

The Compare Function
比較函數:function(a, b){return a-b}
 

Example a-b 小到大  b-a 大到小

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});

 

Find the Highest (or Lowest) Value

找最大或最小值,利用排序,再讀出首或尾欄值

陣列中連接多個數組
陣列A.concat( A數組,B數組,…)         //自己都可以再加入自己的欄值


Array Object

The Array object is used to store multiple values in a single variable:

var cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on.

For a tutorial about Arrays, read our JavaScript Array Tutorial.


Array Properties

Property
Description

constructor
Returns the function that created the Array object's prototype

length
Sets or returns the number of elements in an array

prototype
Allows you to add properties and methods to an Array object

Array Methods

Method
Description

concat()
Joins two or more arrays, and returns a copy of the joined arrays

indexOf()
Search the array for an element and returns its position

join()
Joins all elements of an array into a string

lastIndexOf()
Search the array for an element, starting at the end, and returns its position

pop()
Removes the last element of an array, and returns that element

push()
Adds new elements to the end of an array, and returns the new length

reverse()
Reverses the order of the elements in an array

shift()
Removes the first element of an array, and returns that element

slice()
Selects a part of an array, and returns the new array

sort()
Sorts the elements of an array

splice()
Adds/Removes elements from an array

toString()
Converts an array to a string, and returns the result

unshift()
Adds new elements to the beginning of an array, and returns the new length

valueOf()
Returns the primitive value of an array

http://www.w3schools.com/js/js_array_methods.asp


詳細內容可以參考:

2015年4月16日 星期四

JS Data Types

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:

var length = 16;                                            // Number
var lastName = "Johnson";                            // String
var cars = ["Saab", "Volvo", "BMW"];             // Array
var x = {firstName:"John", lastName:"Doe"};    // Object


The Concept of Data Types

In programming, data types is an important concept.
To be able to operate on variables, it is important to know something about the type.
Without data types, a computer cannot safely solve this:

var x = 16 + 4 + "Volvo";              //Result:20Volvo

var x = "Volvo" + 16 + 4;              //Result:Volvo164 


JavaScript Has Dynamic Types

JavaScript has dynamic types. This means that the same variable can be used as different types:

var x;                    // Now x is undefined
var x = 5;              // Now x is a Number
var x = "John";      // Now x is a String

早期的程式語言對資料型態都非常嚴緊,JS變數的資料型態由存放的值來決定。簡言之就是考慮存入值就好。這一點對使用上是有強大的便利性的,缺點是無法精確的掌控占用資源多寡。因此如果適當的處理資料型態以有效率使用資源,是進階/優化程序的更進一步技術。


JavaScript Strings

JavaScript Numbers

JavaScript Booleans

JavaScript Arrays

JavaScript Objects

Strings,Numbers,Booleans,Arrays,Objects再另作詳解!


The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable:

typeof "John"                        // Returns string
typeof 3.14                           // Returns number
typeof false                          // Returns boolean
typeof [1,2,3,4]                     // Returns object
typeof {name:'John', age:34}   // Returns object

In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object. 


Undefined (未定義)

In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.

var person;                    // Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined. The type will also be undefined.

person = undefined;        // Value is undefined, type is undefined

由這個例子,更能說我上段由值來決定型態,沒有放入值就等同沒有型態。而第二例再宣告是未定義,是不是多此一舉。


Empty Values (空字串)

An empty value has nothing to do with undefined.
An empty string variable has both a value and a type.

var car = "";                // The value is "", the typeof is string


Null (零)

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
在上面解釋Null 在typeof 是一個Object是一個bug。但我突然覺得因為Null的值,即不表明那一類的型態,那麼就是最大型態概說,所以才歸到物件。又就物件導向的觀點,有定義:物件應該包括其它所有類型。

You can empty an object by setting it to null:

var person = null;           // Value is null, but type is still an object

You can also empty an object by setting it to undefined:

var person = undefined;     // Value is undefined, type is undefined


Difference Between Undefined and Null

typeof undefined             // undefined
typeof null                      // object
null === undefined          // false   完全相等是要值/型一致,因此為否。
null == undefined            // true    相等則為真則應該只判斷值而沒對型態。


詳細內容可以參考:

2015年4月15日 星期三

JavaScript Syntax(語法)&Statements(語句)

 

 JavaScript Programs(程序)

  • A computer program is a list of "instructions" to be "executed" by the computer.
  • In a programming language, these program instructions are called statements.(語句)
  • JavaScript is a programming language.
  • JavaScript statements are separated by semicolon.(分號)

Tips: In HTML, JavaScript programs can be executed by the web browser.

 

JavaScript Statements(語句)

JavaScript statements are composed of(語句組成):
Values, Operators, Expressions, Keywords, and Comments.
值,運算元,表達式,關鍵字和註釋

 


JavaScript Values

The JavaScript syntax defines two types of values: Fixed(固定的) values and variable values.
Fixed values are called literals(文字). Variable values are called variables(變量/變數).

 

JavaScript Literals

The most important rules for writing fixed values are:

  • Numbers(數值) are written with or without decimals:

10.50
1001

  • Strings(字符串) are text(文本), written within double or single quotes:

"John Doe"
'John Doe'

  • Expressions(表達式/表現) can also represent fixed values:

5 + 6
5 * 10

JavaScript Variables

In a programming language, variables are used to store(儲存) data values.
JavaScript uses the var keyword to define variables.(Var來定義變量/數)
An equal sign is used to assign values to variables.(等號用來配置值)
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

var x;
x = 6;

 

JavaScript Operators(運算符號)

JavaScript uses an assignment operator ( = ) to assign values to variables:

var x = 5;
var y = 6;

JavaScript uses arithmetic(算術/四則運算) operators ( + - *  / ) to compute values:

(5 + 6) * 10    //己是完整的運算式,只是沒有把結果賦予(=)放置到對象/變數。


Tips: In HTML, JavaScript programs can be executed by the web browser.

JavaScript Statements

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

document.getElementById("demo").innerHTML = "Hello Dolly.";

JavaScript Programs

Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
In this example, x, y, and z is given values, and finally z is displayed:

var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;

tips:JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons( ;)

Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:

a = 5;
b = 6;
c = a + b;

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
語句的結束分號是不必要的,但避免程式解析時的岐異,最好不要省略,自找麻煩!


JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.(忽略多個連續空白間隔)

The following lines are equivalent:

var person = "Hege";
var person="Hege";

A good practice is to put spaces around operators ( = + - * / ):
好習慣:運算符號之間放上空白間隔

var x = y + z;


JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters.
//最佳的可讀性,通常喜歡避免代碼行超過80個字元
If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:
//最好的斷句是在操作符號之後

document.getElementById("demo").innerHTML =
"Hello Dolly.";


JavaScript Code Blocks(代碼塊/分段)

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks this is to define statements to be executed together.
One place you will find statements grouped together in blocks, are in JavaScript functions:

function myFunction() {
    document.getElementById("demo").innerHTML = "Hello Dolly.";
    document.getElementById("myDIV").innerHTML = "How are you?";
}

In this tutorial we use 4 spaces of indentation for code blocks.


JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable

JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.


詳細內容可以參考:

2015年4月14日 星期二

JavaScript簡介

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

  1. HTML to define the content of web pages
  2. CSS to specify the layout of web pages
  3. JavaScript to program the behavior of web pages

what is JavaScript can do?

  1. Change HTML Content
    Example
    document.getElementById("demo").innerHTML = "Hello JavaScript";

  2. Change HTML Attributes

  3. Change HTML Styles (CSS)
    Example
    document.getElementById("demo").style.fontSize = "25px";

  4. Can Validate Data(驗証資料)


JavaScript Where To

  • (比較不負責任說法)簡單的來說就是隨便放,不過大多數專家習慣放head之間或獨立一JS檔,引入使用。
    Keeping all code in one place, is always a good habit.
  • 其實要注恴是瀏覽器解析HTML的流程及JavaScript的解析流程,JS放置的位置會影響到使用中的函數是否會調用到未被定義的值而發生錯誤。

JavaScript Output

  • JavaScript does not have any built-in print or display functions.
    JS沒有任何自有的輸出/打印的函數

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an alert box, using window.alert().
    //出跳出警示視窗。
  • Writing into the HTML output using document.write().
    // will delete all existing (己解析的內容,全清除出)
  • Writing into an HTML element, using innerHTML.
    //選取HTML元素中的innerHTML屬性,就是元素的內文區塊。
  • Writing into the browser console, using console.log(). 瀏覽器控制台

 

JavaScript Comments註解

// 單行:符號後至行結束。不需放在行最前頭。
/*
註解區塊
*/
多行:
/*這個型態符號很容易與HTML混在一起,造成程式碼解譯上的錯誤。能少用就少用。

不過這個在其它語言,幾乎是註解符號的標準了!

JavaScript is Case Sensitive(區分大小寫)

All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.

 

JavaScript and Camel Case

camelCase

當語言可區分大小寫時,在設定「識別名稱ID」上,程序開發會有些習慣用法:

  • 變數名稱:
  • 函數名稱:
  • 常數名稱:

 

JavaScript Character Set

JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters(字元/符), punctuations(標點), and symbols(符號) in the world.

字元集的詳細學習可以到W3shool查看(Complete Unicode Reference.)

詳細內容可以參考:

2015年4月13日 星期一

Hello World!!! 嗨!您好。

SubWay放上的資料,只能定位在學習的筆記型式。
因此,不會特別花時間去註解。

內容即然POST上網,難免會/必定會使用、引述到其它網站的資料,
學習記錄無侵權之意,若您認為該內容屬個人著作所有,
請告知刪除。

使用了電腦/網路幾十年,學習相關內容也斷斷續續,
我不是學這個科系也不是專業的從業人員,純業餘興趣學習。
因此必需先說明,不保證內容的正確性。
尤其是個人異想天開的看法及說明。

這裡偏重於電腦/網路的相關資訊。
利用這個平台來整理這一陣子的學習重點,
內容暫時以這幾個領域的網路技術為主:

前端:HTML(5)、CSS(3)、JavaScript
後端:PHP(5)、ApacheHTML
支援:MySQL(5)、DOM

**************************************************************************
事隔十年重新學習網路的相關技術,
JavaScript、PHP、MySQL正好這十年是發展成熟時期。
翻起當年買而沒看懂的JavaScript書,它依舊難讀和理解。

HTML5和以前的網頁寫法來比較,以前比較易學及直觀,
當年用Dreamweaver3.4.5 。Flash4.5也玩得火熱,
用法這像WORD的所見即所得的法式差不多。
當然,現在也是可以。(雖然我發現程式會不穏定,易當!)
但如果要活用及配會JS、PHP等運用。HTML、CSS本身的精神就無法用軟體取代。
所以,即使不然完完整整的從基礎學習,但也必要再把HTML、CSS的基礎學習一遍,
再才能順利帶過。

雖然前幾年有注意到HTML5的相關資訊,但一直沒深入。
這幾個月,翻了幾本書入門(軟體),一直無法跟十前的技術連結。
碰了一鼻子的灰,老老心靈也生出不少挫折感!
耐心看了不少基礎教學視頻,再有初步的觀念,
原來是以前來用規劃網頁版面的方式大大改變。
加上以前並不那麼熟記標籤這個東西,能看懂一些就很能上手。
所以原想HTML5不會有什麼難的,只要幾本「軟體使用手冊」,
玩一玩就可以混過去但這幾個月的慘痛經驗,
重新建立起新的觀念後,今天才學得稍稍有點入了門。

這不是意味HTML5難學,但如果要深入一點或接觸到JS、PHP...等等!
就避不開程式語言的寫作這一關。因此這其實已是不用領域的東西了!

2015年3月27日 星期五

Subway from Pchome

 

看看最後POST文的日時間,那日期真是令人心驚呀!

一隔就有四年!

這其間已經花時間去鑽研PC,OS,或網頁技術的東西,

沒想到最近又回到這個主題來。

為了方便整理資料,決定還是用Live writer來處理,

幸運的時Google有支援,這個古董產品。

不過也正合適個老古董!

Subway to Html5 CSS3 Javascript and PHP5 MySQL5

這些主流的網頁似乎也來到5的世代!

 

http://mypaper.pchome.com.tw/estony77