JavaScript

  1. HTML: structure layer; CSS: presentation layer; JavaScript: behavior layer. Applying layers of extra information is called progressive enhancement. Web pages that are built using progressive enhancement will almost certainly degrade gracefully.
  2. Events: are js notifications that let you know that when something of interest has happened.
  3. DOM: The DOM is what’s known as an application programming interface (API), the DOM is an API that can be applied using many programming languages in many environments.  
  4. RegExp syntax:
    1 var patt=new RegExp(pattern,modifiers);
    2 
    3 //or more simply:
    4 
    5 var patt=/pattern/modifiers;
  5. The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object.
    function myFunction()
    {
      var str="The rain in SPAIN stays mainly in the plain";  
      var n=str.match(/ain/g);
      document.getElementById("demo").innerHTML=n;
    }

    /*\
    |*| returns: ain,ain,ain
    |*| returns null if no match, and returns the first match if no included 'g'(global match) \
    */
    
    

      <script>
      var str = "Visit W3Schools";
      var patt1 = /w3schools/i;
      document.write(str.match(patt1));
      </script>                            // W3Schools

     

      function myFunction()
      {
        var str = "The rain in SPAIN stays mainly in the plain";
        var n=str.match(/ain/gi);
        document.getElementById("demo").innerHTML=n;
      }

    /*\
    |*| returns: ain,AIN,ain,ain
    |*| returns null if no match, and returns the first match if no included 'g'(global match) \
    */
  6. document.write("<h1>This is a heading</h1>");
  7. A JavaScript alert is a pop-up window, or box, that you can use to display information to the user.
  8. <body onload="...">; <img ... onclick="..." style="cursor:pointer">
  9. 3 types of basic data type: Text, Number, Boolean.
  10. alert boxes only display text.
  11. const TAXRATE = .925;
    var temperature = 21;
    function placeOrder () {form.submit();}
    onclick="placeOrder(this.form)"
    onchange="someFunction()"
  12. Always initialize constants when you create them. No value state: undefined. and NaN is not a number. NaN usually indicates an error in your number data type.
  13. Camel case for objects, and lower camer case for variables and functions. ALLUPPERCASE for constants.
  14. MAKE SURE to manipulate numbers after converting them to numbers.(usually in input)
  15. 1 parseInt("1") + parseInt("2") = 3
    2 parseFloat("someString")
    3 parseFloat("$31.50") = NaN
  16. The toFixed() method converts a number into a string, keeping a specified number of decimals.
    var num = 5.56789;
    var n=num.toFixed(2);     //5.56
    var num = 5.56789;
    var n=num.toFixed();      //6
    var num = 5.56789;
    var n=num.toFixed(10);   //5.5678900000
  17. document.getElementById() method returns an object which can be used when you need the value field.
  18. to tell if the property of an element is a number:
    1 isNaN(document.getElementById("pickupminute").value)  //returns true or false
    // placeOrder() function:
    function placeOrder() {
      if (document.getElementById("name") == "") {
        alert("I'm sorry but you should provide name before submit order!");   
      } else if (document.getElementById("pickupminute").value = "" ||            isNaN(document.getElementById("pickupminute").value)) {
        alert("I'm sorry but you must provide the number of minutes until" + " pickup before submitting an order!");
      } else {
        form.submit();
      }
    }
  19. Subtotal: <input type="text" id="subtotal" name="subtotal" value="" readonly="readonly">
  20. Timer: in millisecond and is based on delays. clearInterval() function requires you to pass it the ID of the interval timer to be cleared, which is returned by the setInterval() function when you create the timer: clearInterval(timerID);
  21. setTimeout() method: setTimeout("alert('2s is over! wake up')", 2000); Interval timer: var timerID = setInterval("alert('Time out!')", 2000); eg: change rock img:
    1 setTimeout("document.getElementById('rockImg').src='rock.png';", 2000);
  22. prompt() method: var theRetrunValue=prompt(msg,defaultText);msg: the message to display in the dialog box, defaultText: default input value. The ReturnValue is the input.
  23. location.reload() method: location.reload(forceGet); the forceGet parameter is of boolean type, true to force get page from server, false to load from cache, which is default.
  24. document.body.clientHeight, document.body.clientWidth; to get client window size. The document object represent the web page itself.
  25. There is a sytle object for every element in a web page, use like: document.getElementById("rockImg").style.height="100px"; use only style.height property will lead to style.width property resize accordingly.
  26. Error report: HeadFirstJavascript: 
    1 function resizeRock() {
    2   document.getElementById("rockImg").style.height = (document.body.clientHeight-100)*0.9  
    3 }
    4 
    5 /* we need to delete the line <!DOCTYPE html> in your html file to see the effect */
  27. onresize event: <body onload="doSomething" onresize="resizeRock()">...</body>
  28. JavaScript destroys ALL variables when the browser closes or the page reloads.
  29. A cookie is a piece of data stored by the browser on the user’s computer. Cookies are a lot like JavaScript variables except that cookies hang around after you close the browser, reload a page, turn off your computer, remodel your house, etc. 
  30.  // Create a cookie with the specified name and value.
     function SetCookie(sName, sValue)
     {
       document.cookie = sName + "=" + escape(sValue);
    // Expires the cookie in one month var date = new Date(); date.setMonth(date.getMonth()+1); document.cookie += ("; expires=" + date.toUTCString()); } // Retrieve the value of the cookie with the specified name. function GetCookie(sName) { // cookies are separated by semicolons var aCookie = document.cookie.split("; "); for (var i=0; i < aCookie.length; i++) { // a name/value pair (a crumb) is separated by an equal sign var aCrumb = aCookie[i].split("="); if (sName == aCrumb[0]) return unescape(aCrumb[1]); } // a cookie with the requested name does not exist return null; } // Delete the cookie with the specified name. function DelCookie(sName) { document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;"; }
  31. Date object: 
    //The setTime() method sets a date and time by adding or subtracting a //specified number of milliseconds to/from midnight January 1, 1970.
    // syntax:Date.setTime(millisec)
    var d = new Date();
    d.setTime(1332403882588);  // Thu Mar 22 2012 04:11:22 GMT-0400 (EDT)
    
    //The toUTCString() method converts a Date object to a string, according to //universal time.
    // syntax: Date.toUTCString()
    var d=new Date();
    var n=d.toUTCString(); // Wed, 20 Mar 2013 18:34:58 GMT
    
    //The getTime() method returns the number of milliseconds between //midnight of January 1, 1970 and the specified date.
    //syntax: Date.getTime()
    var d = new Date();
    var n = d.getTime(); // 1363804503952
  32. escape(),unescape() function:
     1 <script>
     2 
     3 var str="Need tips? Visit W3Schools!";
     4 var str_esc=escape(str);
     5 document.write(str_esc + "<br>")
     6 document.write(unescape(str_esc))
     7 
     8 </script>
     9 
    10 /*\Need%20tips%3F%20Visit%20W3Schools%21
    11 |*|Need tips? Visit W3Schools!
    12 \*/
  33. Comments: //, /* comments */(for css or javascript), <!—  This is a comment in HTML —> 
  34. In JavaScript, if you assign a value to a variable that hasn’t yet been declared, the variable is declared automatically. Although declaring variables beforehand isn’t required in JavaScript, it’s still good programming practice. Variable names can contain letters, numbers, dollar symbols, and underscores. 
  35. when a variable is declared, its data type is also declared. This is called typing. Programming languages that require explicit typing are called strongly typed languages. Because typing is not required in JavaScript, it is a weakly typed language. This means that you can change the data type of a variable at any stage.:
    // The following statements would be illegal in a strongly typed language but //are perfectly fine in JavaScript:
    
    var age = "thirty three"; 
    age = 33;
  36. Data Type: Number, String, Boolean(true;false) are scalar<has one value>,f Array Object
  37. Array:
     1 var beatles=Array(4);
     2 // or
     3 var beatles=Array();
     4 // populating an array:
     5 array[index]=element;
     6 var beatles = Array(4); 
     7 beatles[0] = "John"; 
     8 beatles[1] = "Paul";
     9 beatles[2] = "George"; 
    10 beatles[3] = "Ringo";
    11 // or:
    12 var beatles = Array( "John", "Paul", "George", "Ringo" );
    13 // or:
    14 var beatles = [ "John", "Paul", "George", "Ringo" ];
  38. Object:
    1 var lennon = { name:"John", year:1940, living:false };  // create a lennon object;
    2 var beatles = {};                                       // create a beatles object;
    3 beatles.vocalist = lennon;
  39. javascript has ++, -- operators. You can concatenate string with numbers, but the numbers will be converted to string. The == operator is not strict: 
    var a = false;
    var b = "";
    if (a == b) {            // evaluate to be true;
    alert("a equals b");
    }
    // for a strict comparison, you need === or !== operator which compares value and type.
  40. Logical operators work on Boolean values.
  41.  1 if (condition) {
     2     statements;    
     3 }
     4 
     5 initialize;
     6 while (condition) {
     7     statements;
     8     increment;
     9 }
    10 
    11 do (condition) {
    12     statements;
    13 } while (condition)
    14 
    15 for (initialize; test; alter condition) {
    16     statements;
    17 }
    18 
    19 function shout (arg1, arg2) {
    20     statements;
    21 }
  42. If you use var within a function, the variable will be treated as a local variable. If you don’t use var, the variable will be treated as a global variable.
  43. An object is a self-contained collection of data. Native objects and User-defined object.
    1 // Person is an object;
    2 var jeremy = new Person;
    3 var beatles = new Array();
  44. Math.round(num);  // returns a rounded number. If you create a new instance of the Date object, it will be automatically be prefilled with the current date and time: var current_date = new Date(); var today = current_date.getDay(); // getDay(); getHours(); getMonth();
  45. Objects that are supplied by the web browser are called host objects.  The document object is important.
  46. DOM takes the document that you have written and turns it into an object. The DOM represents the web page that’s currently loaded in the browser window. The browser provides a map (or model) of the page. You can use JavaScript to read this map.
  47. Nodes: Element nodes, Text nodes, Attribute nodes.
  48. typeof operator: returns a string of the argument type;
  49. Each element in a document is an object. getElementById(); getElementsByTagName("p") returns an array contains all the specified tag, such as you can say: alert(getElementsByTagName("li").length); getElementsByClassName();
    1 for (var i=0; i < document.getElementsByTagName("li").length; i++) {
    2     alert(typeof document.getElementsByTagName("li")[i]);
    3 }

    // var shopping = document.getElementById("purchases");

    // var sales = shopping.getElementsByClassName("sale"); 

  50. object.getAttribute(attribute); you can’t use getAttribute/setAttribute on the document object. It can be used on only an element node object. getAttribute method will return null if no such attribute. if (something) is a shorthand way of writing if (something != null). Object.setAttribute(attribute,value);
  51. A pre-DOM method: object.src="new src";
  52. Event handlers are used to invoke some JavaScript when a certain action happens. "onclick onmouseover onmouseout"
  53. The keyword this is a shorthand of saying "this object".
  54. onclick="showPic(this);return false", return false will prevent the default behavior.
  55. childNodes property will return an array of children of an element node: element.childNodes. document.getElementsByTagName("body")[0].childNodes returns an array of children of body element.
  56. The Browser Object Model: BOM; The window object is supported by all browsers. It represent the browsers 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: window.document.getElementById("header"); same as document.getElementById("header"); window size: window.innerHeight property and window.innerWidth property.
  57. nodeType property: node.nodeType returns a number; Element nodes have a nodeType value of 1; Attributes nodes have a nodeType value of 2; Text nodes have a nodeType value of 3; even spaces and linebreaks are nodes and are included in the childNodes array.  nodeValue property: alert(somenode.childNodes[0].nodeValue); this property is to get the value of a node. The nodeValue of a paragraph element is empty. The nodeValue method is very versatile. It can be used to retrieve the value of a node, but it can also be used to set the value of a node.
    1 node.firstChild
    2 // equivalent to node.childNodes[0]
    3 node.lastChild
    4 // equivalent to node.childNodes[node.childNodes.length-1]
  58. If you use JavaScript correctly, your site will still be navigable by users who don’t have JavaScript. This is called graceful degradation
  59. JavaScript uses the open() method of the window object to create new browser windows. window.open(url,name,features)
    1 function popUp(winURL) {
    2     window.open(winURL,"popup","width=320,height=480"); 
    3 }
  60. Using a value of "#" for the href attribute is an attempt to create a blank link. The "#" symbol is used for internal links within documents. e.g. <a href="#" onclick="someFunc();return false;">example</a>
  61. The word this can be used to refer to the current element. <a href="http://www.example.com" onclick="popUp(this.getAttribute('href'));return false;">example</a>, in this case this.getAttribute('href') equals this.href
  62. We can make a hook to an element using class or id: element.event = action; e.g. link[i].onclick=some_function();
     1 window.onload = prepareLinks; 
     2 function prepareLinks() {
     3   var links = document.getElementsByTagName("a");
     4   for (var i=0; i<links.length; i++) {
     5       if (links[i].getAttribute("class") == "popup") { 
     6           links[i].onclick = function() {
     7               popUp(this.getAttribute("href"));
     8               return false; 
     9           }
    10       } 
    11   }
    12 }
    13 
    14 function popUp(winURL) {window.open(winURL,"popup","width=320,height=480"); } 
    15 <a href="http://www.example.com/" class="popup">Example</a>
  63. confirm("something"); : returns true if user click ok, false otherwise.
  64. console.log("somethin"); : Outputs a message to the Web Console.
    1 console.clear();    // clear console information
    2 console.error("some error");    // print out error info
    3 console.warn("some warn");    // print out warn
    4 console.info("some info");    // print out some info
  65. To select for the "he" in "hello", you would write this: "hello".substring(0, 2);
  66. 1 // define a function:
    2 var dividebythree = function (number) {
    3     var val = number / 3;
    4     console.log(val);
    5 };
    6 dividebythree(6);
  67. A variable declared (using var) within a JavaScript function becomes LOCALLocal variables are deleted as soon as the function is completed. Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it. Global variables are deleted when you close the page. If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable. eg: carname="Volvo"; will declare the variable carname as a global variable , even if it is executed inside a function.
  68.  1 // difference between: 
     2 var functionOne = function() {
     3     // Some code
     4 };
     5 function functionTwo() {
     6     // Some code
     7 }
     8 /* The two code snippets you've posted there will, for almost all purposes, behave the same way.
     9 
    10 However, the difference in behaviour is that with the first variant, that function can only be called after that point in the code.
    11 
    12 With the second variant, the function is available to code that runs above where the function is declared.
    13 
    14 This is because with the first variant, the function is assigned to the variable foo at run time. In the second, the function is assigned to that identifier foo at parse time.
    15 
    16 More technical info
    17 
    18 Javascript has three ways of defining functions.
    19 
    20 1. Your first snippet shows a function expression. This involves using the "function" operator to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function" because it does not have to have a name,
    21 2. Your second example is a function declaration. This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.
    22 3. The third way of defining a function is the "Function()" constructor, which is not shown in your original post. It's not recommended to use this as it works the same way as eval(), which has its problems. */

  69. if (typeof(x) !== 'number') return 0; typeof 37 === 'number';
  70. Shift-Enter on Windows allows multi-line entry where Option-Enter works on Mac.
  71. v
posted @ 2013-03-19 02:36  wxwcase  阅读(278)  评论(0编辑  收藏  举报