第十五章:Python の Web开发基础 (二) JavaScript与DOM

本課主題

  • JavaScript 介绍
  • DOM 介绍

 

JavaScript 介绍

JavaScript 是一门编程语言,它可以让网页动起来的,JavaScript 的变量有两种,一个是局部变量;一个是全区变量。怎么分啦?

a = 123;    // 全区变量
var a = 123;  // 局部变量

新版本 JavaScript 的賦值方式

let targetTempC; //let targetTempC = undefined, you can reassign value to targetTempC
const ROOM_TEMP_C = 12.5 //You cannot reassign the value to const later

let 和 var 的分別

你可以提前定义 var 开头的变量,这叫 hoisting ; 但不可以提前定义 let 开头的变量。let 和 var 的区别在于声明变量后作用域的不同应用。

x; // ReferenceError: x is not defined
let x = 3; // we'll never get here -- the error stops execution

x; // undefined 
var x = 3;
x; // 3
function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
let 和 var 的例子

 

JavaScript 的数据类型

JavaScript 有六种数据类型:

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. symbol

JavaScript 的数字类型

  1. parseInt: 
    y = "111"
    "111"
    
    r2 = parseInt(y)
    111
    parseInt( )
  2. parseFloat

JavaScript 的String 类型

var s1 = 'janice'
s1.length // length: 找字符串的长度: 6
s1.charAt(1) // "a"
s1.indexOf('i') // 3
s1.substring(1,4) // "ani"
s1.slice(0,3) // "jan"
'GooD Day! bad DAY'.toLowerCase() // "good day! bad day"
'GooD Day! bad DAY'.toUpperCase() // "GOOD DAY! BAD DAY"
"3" == 3 // true 两个等号 (==) 对比值是否相等
"3" === 3 // false 三个等号 (===) 对比值和类型是否相等

 

JavaScript 的数据类型 Array

  1. 创建数组
    a = []
    a = [11,22,33,44,55]
    a = [ ]
  2. 在数组尾部追加数据:push(ele)
    a = [11,22,33,44,55,66]
    a.push(77,88,99)
    // 9
    
    a
    // [11, 22, 33, 44, 55, 66, 77, 88, 99]
    
    a.push([77,88,99])
    //10
    
    a
    //[11, 22, 33, 44, 55, 66, 77, 88, 99, Array[3]]
    a.push(ele)例子一
    var numbers = [11,22,33,44,55,66];
    
    numbers[length.numbers] = 77;
    numbers.push(77,88,99); // pushing the item to the last part of the array
    numbers.unshift(-22,-11,00); // pushing the item to the first part of the array
    a.push(ele)例子二
  3. 在数最后(尾部)部获取并删取数据:pop( )
    var numbers = [11,22,33,44,55,66];
    var lastValue = numbers.pop() // 调用 pop()会获取数组的最后一个数值
    
    lastValue
    // 66
    
    numbers
    //  [11,22,33,44,55];
    pop( )例子
  4. 在数组头部插入数据:unshift( )
    var numbers = [11,22,33,44,55,66];
    numbers.unshift(-22,-11,00);  // pushing the item to the first part of the array
    unshift( )例子
  5. 在数组头部获取并删取数据:shift( )
    var numbers = [11,22,33,44,55,66];
    var firstValue = numbers.shift();
    
    firstValue
    // 11
    
    numbers
    //  [22,33,44,55,66]
    shift( )例子
  6. 把数组里的元素相加:join e.g. array.join(", ")
    var months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
    ];
    
    for (i=0; i < months.length; i += 1){
        console.log(months.join(', '));
    }
    join()例子

JavaScript 的字典

  1. 创建字典:dic = { }
    a = {'k1':123, 'k2':456}
    //Object {k1: 123, k2: 456}
    JavaScript创建字典
  2. 获取字典里的值:dic['key']
    a = {'k1':123, 'k2':456}
    // Object {k1: 123, k2: 456}
    
    a['k1']
    // 123
    a['k1']
  3. 序列化:把对象变成字符串 JSON.stringify(a);
    a = {'k1':123, 'k2':456}
    // Object {k1: 123, k2: 456}
    
    JSON.stringify(a)
    //"{"k1":123,"k2":456}"
    JavaScript序列化
  4. 反序列化:把字符串变成对象  JSON.parse(b);
    b = '{"k1":123, "k2":456}';
    //"{"k1":123, "k2":456}"
    
    JSON.parse(b);
    //Object {k1: 123, k2: 456}
    JavaScript反序列化
  5. 调用 for-in loop 来获取 JavaScript Object 里的元素
    var person = {
        name: 'Janice',
        country: 'HK',
        age: 25,
        treehouseStudent: true,
        skills: ['JavaScript','HTML','CSS','Python']
    };
    
    for (key in person) {
        console.log(key + ': ' +person[key]);
    };
    
    // results:
    
    /*
    name: Janice
    country: HK
    age: 25
    treehouseStudent: true
    skills: JavaScript,HTML,CSS,Python
    */
    for-in loop 例子

JavaScript 的转义

  1. encodeURL 
  2. encodeComponentURL
  3. decodeURL
  4. decodeComponentURL
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Js-s3</title>
 6 </head>
 7 <body>
 8     <script>
 9         var url = "https://www.sogou.com/web?query=宋仲基";
10         var ret1 = encodeURI(url);
11         var ret2 = encodeURIComponent(url);
12         console.log(ret1);
13         console.log(ret2);
14 
15         var u1 = decodeURI(ret1);
16         var u2 = decodeURIComponent(ret2);
17         console.log(u1);
18         console.log(u2);
19 
20     </script>
21 </body>
22 </html>
23 
24 
25 <!--s3.html:12 https://www.sogou.com/web?query=%E5%AE%8B%E4%BB%B2%E5%9F%BA-->
26 <!--s3.html:13 https%3A%2F%2Fwww.sogou.com%2Fweb%3Fquery%3D%E5%AE%8B%E4%BB%B2%E5%9F%BA-->
27 <!--s3.html:17 https://www.sogou.com/web?query=宋仲基-->
28 <!--s3.html:18 https://www.sogou.com/web?query=宋仲基-->
JavaScript 转义

其他

  1. eval( )
  2. 时间处理,时间有两种:一种是 UTC; 一种是 GMT;
    d = new Date()
    // Sat Nov 26 2016 21:22:59 GMT+0800 (HKT)
    
    d.getFullYear()
    // 2016
    
    d.getHours()
    // 21
    
    d.getUTCDate()
    // 26
    
    d.getUTCHours()
    // 13
    
    d.setMinutes(d.getMinutes() + 2)
    //1480166699597
    JavaScript的时间处理

JavaScript 的条件判断

  1. if-else
    var answer = prompt('What is the best programming language?');
    if (answer === 'JavaScript'){
      alert('You are correct')
    } else {
      alert('JavaScript is the best language!')
    }
    if-else statement
  2. switch case
  3. for loop
    for (var i = 0; i < 10; i++) {
       // do something in here
    }
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>s3</title>
     6 </head>
     7 <body>
     8     <script type="text/javascript">
     9         var li = [11,22,33,44,55];
    10 
    11         // 這是循环它的索引
    12         for(var i = 0; i < li.length; i++){
    13             console.log(i,li[i]);
    14         }
    15 
    16         for(var item in li){
    17             console.log(item,li[item])
    18         }
    19 
    20 //    0 11
    21 //    1 22
    22 //    2 33
    23 //    3 44
    24 //    4 55
    25 
    26         var dic = {'k1':123, 'k2':456};
    27         for(key in dic){
    28             console.log(key, dic[key])
    29         }
    30 //    k1 123
    31 //    k2 456
    32         
    33     </script>
    34 </body>
    35 </html>
    for loop 例子
  4. while loop - 首先查看循环条件,如果符合才会进行循环
    while ( ) {
      // this is the loop
    }
    function randomNumber(upper){
        return Math.floor(Math.random() + upper) + 1;
    }
    
    var counter = 0;
    while (counter < 5) {
        var ranNum = randomNumber(6);
        document.write(ranNum + ' ');
        counter += 1;
    
    }
    while loop 例子
  5. do while loop - 会先运行至少一次循环条件然后才查看循环条件,如果符合才会进行循环。
    do {
      // code for loop goes here
      // it runs AT least one time
    } while ( )
    var randomNumber = getRandomNumer(10);
    var guess;
    var guessCount = 0;
    var correctGuess = false;
    
    function getRandomNumer(upper){
        var num = Math.floor(Math.random() + upper) + 1;
        return num;
    }
    
    do {
        guess = prompt('I am thinking of a number between 1 and 10. What is it?');
        guessCount += 1;
        if (parseInt(guess) === randomNumber) {
            correctGuess = true;
        }
    } while (! correctGuess)
    
    document.write('<h1>You guess the number!</h1>')
    document.write('It took you ' + guessCount + 'tries to guess the correct number ' + randomNumber)
    do while loop 例子 

JavaScript 的异常处理

Python 中的主动抛出异常

raise Exception('xxxxx')

JavaScript  中的主动抛出异常

throw new Error('xxxx')

JavaScript 的函数

  1. 普通函数
    function f1(){
        alert(123)
    };
  2. 匿名函数
    function exec(func, arg){
      func(arg);
    }
    
    exec((something) => {
         console.log(something);
    }, 'Hello!');
  3. 自执行函数
    (function(arg){
        alert(arg);
    })(123)

在 JavaScript 的世界没有块级作用域,但是它采用函数作用域,意思就是说如果你定义的变量在同一个函数里,不论里面有多少个块级,这个变量都可以给其他块级引用;但如果在 fun1( )定义了一个变量,在func2( )就不可以被引用了。

function f2(){
    var arg= 111;
    function f3(){
        console.log(arg);
    }
    return f3;
}
ret = f2();
ret();
JavaScript 作用域

JavaScript的作用域在执行之前已经创建,所以如果全区有一个变量和函数里有相同的变量时候,在调用函数时会调用函数里的,而不是全区的变量。在下面的代码例子中:

  1. 第一步:声明了一个全区的 xo = grandfather;
  2. 第二步:在代码还没被执行时作用域已经在内部定义好了,代码是从上往下被内部定义,定义了 xo = undefined
  3. 第三步:当函数被调用时,代码是从本身的函数作用域往前推来调用的。所以时次调用的结果是找到 inner( )的 xo 变量并打印,因为xo 被赋值成 'myself',所以结果是 'myself'

代码编译时

代码执行过程

xo = 'grandfather';
function func() {
    var xo = 'father';
    function inner() {
        console.log(xo)
    }
    xo = 'myself';
    return inner;
}

var ret = func();
ret();
JavaScript作用域例子

JavaScript 有一个特点,可以提前声明变量,它在编译的过程中会在一个函数里找所有的函数,然后提前声明为 undefined

function f1(){
    // xo = undefined
    console.log(xo)
    var xo = 'janice'
}
JavaScript提前声明
  1. 模态对话框
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input id='i1' type="text" value="请输入关键字" onfocus="Focus()"; onblur="Blur()"/>
        <input id='i2' type="text" />
    
        <script type="text/javascript">
            function Focus(){
    //            console.log('focus');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val == "请输入关键字"){
                    tag.value = "";
                }
            }
    
            function Blur(){
                console.log('blur');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val.trim().length == 0){
                    tag.value = "请输入关键字";
                }
    
            }
    
        </script>
    </body>
    </html>
    模态对话框(例子)
  2. 动态对话框
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .shade{
                position: fixed;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
    
                background-color: black;
                opacity: 0.6;
                z-index: 1000;
            }
            .model{
                height: 200px;
                width: 400px;
                background-color: white;
                position: fixed;
    
                top: 50%;
                left: 50%;
                margin-left: -200px;
                margin-top: -100px;
                z-index: 1001;
            }
            .hide{
                display: none; !important;
            }
        </style>
    </head>
    <body>
        <div style="height: 2000px; background-color: palegoldenrod">
            <input type="button" value="Press Me" onclick="ShowModel();"/>
        </div>
        <div id="shade" class="shade hide"></div>
        <div id="model" class="model hide">
    
            <!--<a href="javascript:void(0)" onclick="HideModel();">Cancel</a>-->
            <input type="button" value="Cancel" onclick="HideModel();"/>
        </div>
    
        <script>
            function ShowModel(){
                var t1 = document.getElementById('shade');
                var t2 = document.getElementById('model');
    
                t1.classList.remove('hide');
                t2.classList.remove('hide');
            }
            function HideModel(){
                var t1 = document.getElementById('shade');
                var t2 = document.getElementById('model');
    
                t1.classList.add('hide');
                t2.classList.add('hide');
            }
        </script>
    </body>
    </html>
    动态对话框(例子)
  3. 选框
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>s7</title>
    </head>
    <body>
        <input type="button" value="全选" onclick="CheckAll()" />
        <input type="button" value="取消" onclick="CancelAll()" />
        <input type="button" value="反选" onclick="ReverseAll()" />
    
        <table border="1">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>用户名</th>
                    <th>密码</th>
                </tr>
            </thead>
            <tbody id="tb">
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>1</td>
                    <td>11</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>2</td>
                    <td>22</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>3</td>
                    <td>33</td>
                </tr>
    
            </tbody>
        </table>
    
        <script type="text/javascript">
            function CheckAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++){
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
                    ck.setAttribute('checked','checked');
                }
            }
            function CancelAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++) {
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
                    ck.removeAttribute('checked');
                }
            }
            function ReverseAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++) {
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
    
                    if (ck.checked){
                        ck.checked = false;
                        ck.removeAttribute('checked');
                    }else {
                        ck.checked = true;
                        ck.setAttribute('checked','checked');
                    }
    
                }
            }
        </script>
    </body>
    </html>
    选框(例子)

 

DOM 介绍

把整个 HTML 弄成一个文档树,然后调用 DOM 来操作,包括新增、删除、更新 HTML中的 Tag

JavaScript Document is a global object representing the HTML and the web page. As with JavaScript, you are interacting with the webpage by changing the document.

  1. Selecting elements on the page
    const element = document.getElementById('a') // <ul id='a'>111</ul>
    const elements = document.getElementsByClassName('myClass') //<div class='myClass'>111</div>
    const element = document.getElemenetsByName('animals') //<input name="animal" type="checkbox" value="Cats">
    const elements = document.getElementsByTagName('p') // [<p>,<p>,<p>]
    const element = document.querySelector('li')
    const elements = document.querySelectorAll('li')
  2. Manipulating elements 
    const toggleList = document.getElementById('toggleList');
    const listDiv = document.querySelector('.list');
    
    const descriptionInput = document.querySelector('input.description');
    const descriptionP = document.querySelector('p.description'); //specify the paragraph with the description class
    const descriptionButton = document.querySelector('button.description');
    
    const addItemInput = document.querySelector('button.addItemInput');
    const addItemButton = document.querySelector('button.addItemButton');
    
    const removeItemButton = document.querySelector('button.removeItemButton');
    
    
    toggleList.addEventListener('click', () => {
      if (listDiv.style.display == 'none'){
      toggleList.textContent = 'Hide List';
      listDiv.style.display = 'block';
    } else {
      toggleList.textContent = 'Show List';
      listDiv.style.display = 'none';
    }                            
    });
    
    descriptionButton.addEventListener('click', () => {
      descriptionP.innerHTML = descriptionInput.value + ':';
      descriptionInput.value = '';
    });
      
    addItemButton.addEventListener('click', () => {
      let ul = document.getElementsByTagName('ul')[0];
      let li = document.createElement('li');
      li.textContent = addItemInput.value;
      ul.appendChild(li);
    });
      
    
    removeItemButton.addEventListener('click', () => {
      let ul = document.getElementsByTagName('ul')[0];
      let li = document.querySelector('li:last-child');
      ul.removeChild(li);
    });
      
    完整例子
    • innerHTML - 获取 HTML 的 tag 中文本+HTML Tag 的内容
      let ul = document.querySelector('ul')
      ul.innerHTML
      
      /*
      "
            <li>grapes</li>
            <li>amethyst</li>
            <li>lavender</li>
            <li>plums</li>
          "
      */
      innerHTML
    • innerText - 获取 HTML 的 tag 中文本的内容
      <div>这是本文内容</div>
    • value - 获取 HTML 的 tag 中的值
    • textContent - 只获取 HTML tag 中的字符串
      let ul = document.querySelector('ul')
      ul.textContent
      
      /*
      "
            grapes
            amethyst
            lavender
            plums
          "
      */
      textContent
    • input.className
      input.type = 'checkbox'
      obj.innerHTML = '<li>apple</li>'
      obj.textContent = 'apple'
      obj.style.color = 'red'
      obj.style.display = 'none'
      obj.style.display = 'block'
      obj.style.backgroundColor = 'lightblue'
      // Element Style properties
      document.createElement('div')
      parentElement.appendChild(childElement)
      parentElement.removeChild(childElement)
  3. Listening for user actions 这个用法是不在 HTML Tag 中加入 event,而是在 JavaScript 中加入监听事件 addEventListener( ) 
    EventTarget.addEventListener(type, (event) => {
       console.log(event.target);
    });
    <!DOCTYPE html>
    <html>
      <head>
        <title>JavaScript and the DOM</title>
        <link rel="stylesheet" href="css/style.css">
      </head>
      <body>
        <h1 id="myHeading">JavaScript and the DOM</h1>
        <p>Making a web page interactive</p>
        <input type='text' id="myTextInput"/>
        <button id="myButton">Change headline color</button>
      <script>
      const myHeadingBtn = document.getElementById('myHeading');
      const myButtonBtn = document.getElementById('myButton');
      const myTextInputBtn = document.getElementById('myTextInput');
      
      myButtonBtn.addEventListener('click', ()=> {
        myHeadingBtn.style.color = myTextInputBtn.value;
      });  
      </script>
      </body>
    </html>
    addEventListener 例子
  4. Checking the sibling of the node
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div>
            <ul>
                <li id='a'>apple</li>
                <li id='b'>banana</li>
                <li id='w'>waterlemon</li>
                <li id='l'>lemon</li>
                <li id='g'>grapes</li>
            </ul>
        </div>
    </body>
    </html>
    html example code
    • 第一步、首先找出它的 id

      waterlemon = document.getElementById('w') 
      //這里获取了 <li id='w'>waterlemon</li> 数据
      document.getElementById('w')
    • 第二步、可以找这里 id=w 的父亲 Node:
      ul = waterlemon.parentNode 
      // 调用 parentNode 取了 <li></li> 的HTML父亲, 即 <ul></ul>
      
      ul2 = waterlemon.parentElement
      parent
    • 第三步、可以找这个父亲 Node 的儿子 Node:
      ul.childNodes 
      // 调用 childNodes 取了 <div></di> 的HTML儿子和一些text, 即下面一系列的 <li></li>
      
      ul.children 
      //只获取 ul 的HTML 儿子
      child
    • 第四步、找父亲 Node 的第一个儿子
      ul.firstChild
      ul.firstElementChild 
      //获取第一个 ul 的HTML 儿子, e.g. <li id='a'>apple</li>
      firstChild
    • 第五步、找父亲 Node 的最后一个儿子
      ul.lastChild
      ul.lastElementChild //获取第一个 ul 的HTML 儿子, e.g. <li id='g'>grapes</li>
      lastChild
    • 第六步、找儿子 Node 的前一个兄弟(大哥) Node
      waterlemon.nextSibling
      waterlemon.nextElementSibling // 获取 waterlemon 的下一个 HTML 的同级兄弟, e.g. <li id='l'>lemon</li>
      nextSibling
    • 第七步、找儿子 Node 的后一个兄弟(弟弟) Node
      waterlemon.previousSibling
      waterlemon.previousElementSibling // 获取 waterlemon 的上一个 HTML 的同级兄弟, e.g. <li id='b'>banana</li>
      previousSibling

操作内容

  1. 创建标签
    • 字符串的形式
    • 对象的形式
  2. 操作标签
    p1 = document.getElementById('p1')
    
    var tag1 = "<a>beforeEnd</a>"
    var tag2 = "<a>beforeBegin</a>"
    var tag3 = "<a>afterEnd</a>"
    var tag4 = "<a>afterBegin</a>"
    
    p1.insertAdjacentText("beforeEnd",tag1)
    p1.insertAdjacentText("beforeBegin",tag2)
    p1.insertAdjacentText("afterEnd",tag3)
    p1.insertAdjacentText("afterBegin",tag4)
    
    <a>111</a> //beforeBegin
    <div id="p1">
        <a>111</a> //afterBegin
        <p>hhh</p>
        <a>111</a> //beforeEnd
    </div>
    <a>111</a> //afterEnd
    操作标签
tags = document.getElementsByTagName('div')
//[div.c1.c2.c3]
tags[0]
//<div class="c1 c2 c3">123</div>
tags[0].className
//"c1 c2 c3"
tags[0].classList
//["c1", "c2", "c3"]
tags[0].classList.add('c4')
tags
//[div.c1.c2.c3.c4]
tags[0].classList.remove('c4')
tags
//[div.c1.c2.c3]
View Code

案例实战 

  1. 小案例一:搜索框
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>S3</title>
    </head>
    <body>
        <input id='i1' type="text" value="请输入关键字" onfocus="Focus()"; onblur="Blur()"/>
        <input id='i2' type="text" />
    
        <script type="text/javascript">
            function Focus(){
                console.log('focus');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val == "请输入关键字"){
                    tag.value = "";
                }
            }
    
            function Blur(){
                console.log('blur');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val.trim().length == 0){
                    tag.value = "请输入关键字";
                }
    
            }
    
        </script>
    </body>
    </html>
    搜索框
  2. 小案例二:多选反选取消
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>s7</title>
    </head>
    <body>
        <!--<div id="p1">-->
            <!--<p>hhh</p>-->
        <!--</div>-->
        <input type="button" value="全选" onclick="CheckAll()" />
        <input type="button" value="取消" onclick="CancelAll()" />
        <input type="button" value="反选" onclick="ReverseAll()" />
    
        <table border="1">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>用户名</th>
                    <th>密码</th>
                </tr>
            </thead>
            <tbody id="tb">
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>1</td>
                    <td>11</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>2</td>
                    <td>22</td>
                </tr>
                <tr>
                    <td><input type="checkbox"/></td>
                    <td>3</td>
                    <td>33</td>
                </tr>
    
            </tbody>
        </table>
    
        <script type="text/javascript">
            function CheckAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++){
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
                    ck.checked = true;
                }
            }
            function CancelAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++) {
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
                    ck.checked = false;
                }
            }
            function ReverseAll(){
                var tb = document.getElementById('tb');
                var trs = tb.children;
                for(var i=0; i < trs.length; i++) {
                    var current_tr = trs[i];
                    ck = current_tr.firstElementChild.firstElementChild;
    
                    if (ck.checked){
                        ck.checked = false;
                    }else {
                        ck.checked = true;
                    }
    
                }
            }
        </script>
    </body>
    </html>
    多选反选取消
  3. 小案例三:点赞功能
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .item{
                padding: 50px;
                position: relative;
            }
            .item span{
                position: absolute;
                top: 49px;
                left: 71px;
                opacity: 1;
                font-size: 18px;
                color: green;
            }
        </style>
    </head>
    <body>
        <div class="item">
            <a onclick="Favor(this);">赞1</a>
        </div>
        <div class="item">
            <a onclick="Favor(this);">赞2</a>
        </div>
        <div class="item">
            <a onclick="Favor(this);">赞3</a>
        </div>
        <div class="item">
            <a onclick="Favor(this);">赞4</a>
        </div>
        <script type="text/javascript">
            function Favor(ths){
    //            console.log(ths.parentElement);
    
                var top = 49;
                var left = 71;
                var op = 1;
                var fontSize = 18;
    
                var tag = document.createElement('span');
                tag.innerText = "+1";
                tag.style.position = "absolute";
                tag.style.top = top + "px";
                tag.style.left = left + "px";
                tag.style.opacity = op ;
                tag.style.fontSize = fontSize + "px";
                ths.parentElement.appendChild(tag);
    
                var interval = setInterval(function () {
                    top -= 10;
                    left += 10;
                    fontSize += 5;
                    op -= 0.1;
    
                    tag.style.top = top + "px";
                    tag.style.left = left + "px";
                    tag.style.opacity = op;
                    tag.style.fontSize = fontSize + "px";
    
                    if (op <= 0.2){
                        clearInterval(interval);
                        ths.parentElement.removeChild(tag);
                    }
    
                }, 50)
            }
    
        </script>
    </body>
    </html>
    点赞功能
  4. 小案例四:返回顶部
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>s11</title>
        <style>
            .back{
                position: fixed;
                right: 20px;
                bottom: 20px;
                color: red;
            }
            .hide{
                display: none;
            }
        </style>
    </head>
    <body onscroll="BodyScroll();">
        <div style="height: 2000px; background-color: #dddddd; overflow: auto"></div>
        <div id='back' class="back hide" onclick="BackTop();">返回顶部</div>
        <script type="text/javascript">
            function BackTop(){
                document.body.scrollTop = 0;
            }
            function BodyScroll(){
                var s = document.body.scrollTop;
                var t = document.getElementById('back');
                if (s >= 100){
                    t.classList.remove('hide')
                } else {
                    t.classList.add('hide')
                }
            }
        </script>
    </body>
    </html>
    返回顶部
  5. 小案例五:通过 JavaScript 在提交数据
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title></title>
     6 </head>
     7 <body>
     8     <form id="f1">
     9         <input id='i1' type="text"/>
    10         <input type="submit", value="提交" />
    11         <a onclick="Submit()";>提交</a>
    12     </form>
    13 
    14     <script type="text/javascript">
    15         function Submit(){
    16             var form = document.getElementById('f1');
    17             form.submit();
    18         }
    19     </script>
    20 </body>
    21 </html>
    通过 JavaScript 在提交数据例子
  6. 小案例六:判断 form 是吾可以提交 onclick="return SubmitForm();
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>s16</title>
     6 </head>
     7 <body>
     8     <form action="http://www.baidu.com">
     9         <input id="username" type="text"/>
    10         <input type="submit" value="提交" onclick="return SubmitForm();"/>
    11     </form>
    12     <script>
    13         function SubmitForm() {
    14             var user = document.getElementById('username');
    15             if (user.value.length > 0) {
    16                 //可以提交
    17                 return true;
    18             } else {
    19                 //不可以提交和提示错误
    20                 alert('用户名输入不能为空');
    21                 return false;
    22             }
    23         }
    24     </script>
    25 </body>
    26 </html>
    判断 form 是吾可以提交例子

DOM 事件

绑定事件,把一些 HTML Tag,比如 <button>, <input> 绑定以下事件

  1. onfocus,当mouse 点击时进行操作
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>S3</title>
    </head>
    <body>
        <input id='i1' type="text" value="请输入关键字" onfocus="Focus()"; onblur="Blur()"/>
        <input id='i2' type="text" />
    
        <script type="text/javascript">
            function Focus(){
                console.log('focus');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val == "请输入关键字"){
                    tag.value = "";
                }
            }
    
            function Blur(){
                console.log('blur');
                var tag = document.getElementById('i1');
                var val = tag.value;
                if (val.trim().length == 0){
                    tag.value = "请输入关键字";
                }
    
            }
    
        </script>
    </body>
    </html>
    onfocus 例子
  2. onclick,点击的时进行操作
  3. ondbclick
  4. onblur,当mouse 离开时进行操作
  5. onchange,当有改变时进行操作
onkeydown
onkeyup
onkeypress
onload
onmousedown
onmouseover
onmouseout
onmousemove
onmouseup
onrest
onresize
onselect
onsubmit
onunload
onload
其他 DOM-event

全区绑定事件

window.onkeydown = function(event){
    console.log(event)
}

 

 

 

參考資料 

银角大王:Python开发【第十一篇】:JavaScript | Python开发【第十二篇】:DOM

金角大王:

其他:jQuery 中文文档 | 事件

 

posted @ 2016-11-27 11:24  無情  阅读(362)  评论(0编辑  收藏  举报