Tuesday, February 4, 2014

Study for JavaScript

<Introduction to JavaScript>


1. Embedded inside <HEAD></HEAD>

For Example:


<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch5_1_1.htm</title>
    <script>
    function&nbspshowmessage(){

        alert("JavaScript inside <HEAD> section"); 
    }
    </script>
</HEAD>
<BODY onload="showmessage()">
<H2>JavaScript Sample inside <HEAD> section </H2>
<HR />
Handle actions inside <HEAD>
</BODY>
</HTML>

2. Embedded inside <BODY></BODY>

For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch5_1_2.htm</title>
</HEAD>
<BODY 
<H2>JavaScript Sample inside <BODY> section </H2>
<HR />
<script>
    alert("JavaScript Sample inside <BODY> section");
</script>
Handle actions inside <BODY>
</BODY>
</HTML>

3. An individual external JavaScript file

For Example:


<script src="Ch_1_1_3.js"></script>

<script language="JavaScript" src="Ch5_1_3.js"></script>
<script language="text/javascript" src="Ch5_1_3.js"></script>

Notes: Cannot use <script .../> !!!

<Show the Developer Bug for JavaScript in IE>


After opening IE browser, press Tools > F12 to show script bugs.



<JavaScript Basic Format>

1. Closing Tag (;)

For Example:

var intBalance = 1000;
intBalance += 100;
document.write("First JavaScript code");

var strName = "Chan"; var intBalance = 1000; var strNo = "1234567";


2. Block ({ })

For Example:

function showMessage(){
    alert("JavaScript inside <HEAD> section");
}
 
3. Comment (// or /* */);

For Example:

// Comments
document.write("<h2>Hello World!</h2>");


4. Long statement

For Example:

document.write
("First JavaScript Code");


<Declare JavaScript variables>

Case-sensitive:
Showmessage() != show message() != ShowMessage()

variable types: boolean (true or false), number, string (' or ")

var strName;
var strName, intBalance;

1. Boolean
var blnSex = true;

2. Number
var intBalance = 1000;

3. String
var strName = "James Brown";

For Example:



<!DOCTYPE html>

<HTML>

<HEAD>

    <title>Ch5_3_1.htm</title>

</HEAD>

<BODY>
<script>
    // comments for variables
    var strName = "Hello World";
    var intBalance = 100;
    var blnSex = true;

    // show variables values

    document.write("User Name:" + strName + "<br/>");
    document.write("Sex:" + blnSex + "<br/>");
    document.write("Account:" + intBalance);
</script>

</BODY>

</HTML>

The result should be:











Notes: In JavaScript, no need to declare a variable before use. 


4. Null





5. Array


6. Undefined

<JavaScript Reserved words>

  1. break
  2. case
  3. catch
  4. continue
  5. debugger
  6. default
  7. delete
  8. if 
  9. else
  10. for
  11. do
  12. while
  13. true
  14. false
  15. finally
  16. function
  17. return
  18. try
  19. void
  20. var
  21. with
  22. typeof
  23. switch
  24. instanceof
  25. in
  26. new
  27. throw
  28. null
  29. this


<JavaScript Naming>

1. Cannot use Number as init naming of variable.
2. Cannot use full stop (.) as init naming of variable.
3. Can use Character or (_)



<Check if JavaScript variables exist>


var intBalance = 100;
if (intBalance) 

    document.write("intBalance exist<br/>");

else

    document.write("intBalance not exist<br/>");


The result should be:








var intBalance;

If not exist, the result value is undefined.


The result should be:







上述if 條件檢查變數值是否為undefined, 如果false表示存在,否則變數不存在,問題是變數 intBalance 需要是已經宣告的變數,如果變數根本沒有宣告,此時的if 條件會導致 JavaScript 執行錯誤,不過,在瀏覽器並不會顯示錯誤訊息,只是根本忽略此 if 條件。

if (window.strName
    document.write("strName exist: " + window.strName + "<br/>");
else
    document.write("strName not exist: " + window.strName + "<br/>");


The result should be:








正確的變數檢查方法是使用Window 物件,因為JavaScript 宣告或使用的變數都屬於 Window 物件的屬性,換句話說,我們只需檢查 Window 物件的屬性,就可以知道變數是否存在,如上所示。

上述 if 條件不論變數是否宣告,都可以檢查變數是否存在,不過,此 if 條件的程式碼並不適用boolean variable 檢查。






<JavaScript Escape>




\b          Backspace

\f          FF, Form feed        

\n          LF, Line feed 換行符號

\r          CR,Enter 鍵
\t          Tab 鍵
\'          ' 符號 
\"          " 符號
\\          \ 符號



<JavaScript Data Type Conversion>

If number + string, then converted as "String".
If boolean + string, then converted as "String".
If boolean + number, then converted as "Number".



<!DOCTYPE html>

<HTML>

<HEAD>

    <title>Ch5_6_1.htm</title>
</HEAD>
<BODY> 
<script>
     // Variable comments
     var strName, intBalance, blnSex;
     // Assign values to variables
     strName = "Hello World";
     intBalance = 1000;
     blnSex = true;

     // show the results
     output = strName + intBalance; 
     // expect the value as "Hello World 1000" (String)
     document.write(output + " : " + typeof(output)+ "<br/>");
     
     output = strName + blnSex;
     // expect the value as "Hello World true" (String)
     document.write(output + " : " + typeof(output)+ "<br/>");
    
     output = blnSex + intBalance;
     // expect the value as "true 1000" (Number)
     document.write(output + " : " + typeof(output)+ "<br/>");

     blnSex = false; // reset the boolean variable
     output = blnSex + intBalance;
     // expect the value as "false 1000" (Number)
     document.write(output + " : " + typeof(output)+ "<br/>");

</script>
</BODY>


</HTML>

The result should be:












<JavaScript common functions> 

1.parseInt()

parseInt("3 page")           value = 3 // 字串開頭為 Number
parseInt("3.2")                 value = 3 // 雖然是 float number, 不過只取出整數
parseInt("Page 3")           value = NaN // 字串開頭不是 Number,NaN = Number a number
parseInt("18ff value", 16) value = 6399 // 將字串轉成 16 進位數值,也就是18ff
parseInt("18ff value", 10) value = 18 // 將字串轉成 10 進位數值,也就是18
parseInt("18ff value", 8)   value = 1 // 將字串轉成 8 進位數值,因為數值不能超過8,所以為1

2. parseFloat()

3. eval()

Convert String as Number for calculation.

eval("20 + 4 + 5")                  value = 40 
eval("intBalance = 1000")     value = 1000
eval("5 > 4")                          value = true

4. typeof()




null.....







<JavaScript Control> 



1. == (Equal), != (Not Equal), < (Less than), > (Larger than), <= , >= , ! (NOT), && (AND), || (OR)



For Example:


<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch6_2_1.htm</title>
</HEAD>
<BODY>
<script>
    var a = true;
    var b = false;
    
    document.write("Less than: 6<3, the result: " + (6<3) + "<br/>");
    document.write("Larger than: 6>3, the result: " + (6>3) + "<br/>");
    document.write("Less than or equal to: 6<=3, the result: " + (6<=3) + "<br/>");
    document.write("Large than or equal to: 6>=3, the result: " + (6>=3) + "<br/>");
    document.write("Equal to: , the result: " + (6=3) + "<br/>");
    document.write("Not equal to: 6<3, the result: " + (6!=3) + "<br/>");
    document.write("a = " + a + " b = " + b + "<br/>");
    document.write("NOT !a = " + !a + "<br/>");
    document.write("NOT !b = " + !b + "<br/>");
    document.write("AND a && b = " + a&&b + "<br/>");
    document.write("OR a || b = " + a||b + "<br/>");
</script>
</BODY>
</HTML>
The result should be:










For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch6_2_2.htm</title>
</HEAD>
<BODY>
<script>
    var a = true;
    var b = false;

    var x = a && 10;
    var y = b && 5;
    
    document.write("a = " + a + " b = " + b + "<br/>");//a = true b = false
    document.write("x = a && 10 =  " + x + "<br/>"); // x = a && 10 = 10
    document.write("y = b && 5 = " + y + "<br/>"); // y = b && 5 = false

    var c = 1;
    var d = 1;
    var z = 10;
    z = (c == d) && 20;
    document.write("c = " + c + " d = " + d "<br/>");
    document.write("z = (c==d) && 20 = " + z + "<br/>");

    z = 10;
    if(c == d) z = 20;
    document.write("z = " + z + "<br/>");
</script>
</BODY>
</HTML>


The result should be:













2. Looping
2_1) if/else ... else

For Example:

var intAge = 20;
document.write("Age: " + intAge + "<br/>");
if(intAge <= 18)
    document.write("You are a kid.<br/>");
else
    if (intAge >=65)
        document.write("You are an elderly.<br/>");
    else
        document.write("You are an adult.<br/>");


The result should be:







2_2) switch

For Example:
var strPayment = "master";
switch(strPayment){
    case "cash":
        document.write("Please use cash!<br/>");
    case "visa":
        document.write("Please use Visa for payment!<br/>");
    case "master":
        document.write("Please use Master for payment!<br/>");
    default:
        document.write("Unknown payment method!<br/>");
}

The result should be:






var strPayment = "xxxxxx";

The result should be:
 




2_3) ?:

?: Same as if/else.

For Example:

var strHours = "";
dtHour = 20;
strHours = (dtHour >=12) ? " PM" : " AM";
dtHour = (dtHour >=12) ? dtHour-12 : dtHour;
document.write("Current time: " + dtHour + strHours + "!<br/>");

The result should be:





dtHour = 4;

The result should be:




 
2_4) for

For Example:

var i;
var intSum = 0;

for (i = 1; i <=5; i++){
    document.write("Integer: " + i + "<br/>");
    intSum += i;
}

document.write("<br/>Total: " +intSum + "<br/>");

The result should be:













2_5) for/in


For Example:


<script>

    var prop;

    var objAddress = new Object();

   

    objAddress.name = "Peter Pan";

    objAddress.age = "40";

    objAddress.phone = "02-22222222";

    objAddress.email = "test@test.com";

   

    for (prop in objAddress){
        document.write("Attribute:" + prop + "=" +
                        objAddress[prop] + "<br/>");
    }
   
    var arrTips = new Array(100, 200, 500);
    for (ele in arrTips){
        document.write("Element:" + ele + "=" +
                        arrTips[ele] + "<br/>");
    }
</script>

 
The result should be:














  
2_6) while

For Example:

var intSum = 0;
var i = 0;
while(i <= 6){
    document.write("Integer: " + i + "<br/>");
    intSum += i;
    i++;
}
document.write("<hr/>Total: " + intSum + "<br/>");

The result should be:
















2_7) do/while

For Example:

var i = 1;
var intSum = 0;

do{
    document.write("Integer: " + i + "<br/>");
    intSum += i;
    i++;
} while (i <= 6);

document.write("<hr/>Total: " + intSum + "<br/>");

The result should be:











 


3. break / continue

For Example:

var target = 34;
var number = 0;
var times = 0;

do {
    number = window.prompt("Please input the number: ", number);
    if (number == null || number == target)
        break;
    if (number > target){
        alert(number + "is too large!");
        times++;
        continue;
    }
    else
        if (number != target){
            alert(number + "is too small!");
            time++;
            continue;
        }
} while (true);

if(number == null){
    document.write("Don't guess! The number is: " + target + "<br/>");
} else {
    document.write("Bingo! The number is: " + target + "<br/>");
    document.write("Total number of times for guess: " + (times+1)+"<br/>");
}

The result should be:
 








<JavaScript Function Call> 

1. Convert URL code:
a.escape()
b. unescape()

Notes:
English string and number --> no need to encode
backspace, symbol --> convert as %XX string, XX in 16-ASCII, convert backspace as %20
Chinese string --> convert as %uXXXX string, XXXX in 16-code


For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch7_1_2.htm</title>
    <meta charset="utf-8"/>
</HEAD>
<BODY>
<script>
    var strMsg = "HTML 5+CSS3+JavaScript網頁製作徹底研究";
    var strURLcode, strOriginal;

    strURLcode = escape(strMsg);
    document.write("Original string: " + strMsg + "<br/>");
    document.write("URL code: " + strURLcode + "<br/>");

    strOrignal = unescape(strURLcode);
    document.write("Uncode string: " + strOriginal + "<br/>");
</script>
</BODY>
</HTML>

The result should be:


2a. custom function call

For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch7_2_1.htm</title>
    <script>
    function writeString(){
        document.write("Welcome to use custom function<br/>");
    }
    </script>

</HEAD>

<BODY>
<script>
   writeString();

   document.write("Succeed to call custom function<br/>");
</script
</BODY>
</HTML>
The result should be:






2b. custom function call with parameter

For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch7_2_2.htm</title>
    <script>
    function writeString(strMsg, intNumber){
        for(var i=1; i<=intNumber; i++){
            document.write(strMsg + "<br/>");
        }
    }
    </script>

</HEAD>

<BODY>
<script>
   writeString("HTML5 +CSS3+JavaScript",3);
</script

</BODY>
</HTML>


The result should be:








2c. custom function call with return value

For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch7_2_3.htm</title>
    <script>
    function convert2F(c){
        var f;
        f = (9.0 * c) / 5.0 + 32.0;
        return f;
    }
  
    function convert2C(f){
        var c;
        c = (5.0 / 9.0) * (f -32);
        return c;
    }
    </script>

</HEAD>

<BODY>
<script>
   var f = convert2F(20);
   document.write("C 20: " + f + "F <br/>");
 
   var c = convert2C(86);
   document.write("F 86:" + c + "C <br/>");
</script

</BODY>
</HTML>


The result should be:









2d. custom function call with new

For Example:

<!DOCTYPE html>
<HTML>
<HEAD>
    <title>Ch7_2_4.htm</title>
    <script>
    function funcA(c, b){
        c++;
        b = false;
        document.write("funcA: " + c + "/" + b + "<br/>");
    }
  
    function funcB(objA, a){
        objA.name = "Peter Pan";
        a = "Kelvin";
        document.write("funcB: " + objA.name + "/" + a + "<br/>");
    }
    </script>

</HEAD>

<BODY>
<script>
   var c = 1;
   var b = true;
   var a = "Peter Pan";
 
   var objA = new Object();
   objA.name = "Peter Pan";
 
   document.write("Before Call funcA: " + c + "/" + b + "<br/>");
 
   funcA(c, b);
   document.write("After Call funcA: " + c + "/" + b + "<br/>");
   document.write("Before Call funcB: " + objA.name + "/" + a + "<br/>");
 
   funcB(objA, a);
   document.write("After Call funcB: " + objA.name + "/" + a + "<br/>");
</script>

</BODY>
</HTML>

The result should be:











3. Local variables VS Global variables

4. Recursive functions



<JavaScript Debugging> 

1. With Visual Studio


<JavaScript Object> 

1. Intrinsic Objects
2. Custom Objects
3. Host Objects




<JavaScript BOM> 

BOM = Browser Object Model

winID = window.open("Ch10_2_3a.htm", "JavaScript");

window.close();



<JavaScript DOM> 
DOM = Document Object Model

use DOM for HTML and XML files, so called "HTML DOM".
Nodes

DOM Core
DOM HTML
DOM Level 0 / 1 / 2 / 3

Common Methods:
getElementById()

<p><a id="google" href="http://www.google.com">Google</a></p>

var a = document.getElementById("google");


nodeName VS tagName

alert(a.nodeName + " - " + a.href);
alert(btn.tagName + " - " + btw.type);




getElementsByTagName()
getElementsByName()
getElementsByClassName()
item()
use NodeList

Method for CSS:
querySelectorAll()
querySelector()


innerHTML
outerHTML
textContent



<JavaScript Event Handlers> 

No comments:

Post a Comment