JavaScript(7)——DOM

什麼是 DOM?

DOM是 Document Object Model(文檔對象模型)的縮寫css

DOM是 W3C(萬維網聯盟)的標準。html

DOM 定義了訪問 HTML 和 XML 文檔的標準:node

「W3C 文檔對象模型 (DOM) 是中立於平臺和語言的接口,它容許程序和腳本動態地訪問和更新文檔的內容、結構和樣式。」

W3C DOM 標準被分爲 3 個不一樣的部分:編程

  • 核心 DOM - 針對任何結構化文檔的標準模型,不管是XML,HTML以及其它的標記語言都是通用的
  • XML DOM - 針對 XML 文檔的標準模型
  • HTML DOM - 針對 HTML 文檔的標準模型

什麼是 HTML DOM?

HTML DOM 是:bootstrap

  • HTML 的標準對象模型
  • HTML 的標準編程接口
  • W3C 標準

HTML DOM 定義了全部 HTML 元素的對象和屬性,以及訪問它們的方法。數組

換言之,HTML DOM 是關於如何獲取、修改、添加或刪除 HTML 元素的標準。緩存

區別

對於核心DOM,  API簡單,原理簡單,編碼複雜;app

HTML DOM,API複雜,編程形象化,編碼輕鬆dom

對於核心DOM只有標記語言的概念,並不認識各個標籤的含義,標記語言是由節點互相嵌套而成;ui

  • 元素結點
  • 屬性節點
  • 文本節點
  • 註釋結點

核心DOM API:

document.createElement(nodename)

The createElement() method creates an Element Node with the specified name.

document.createTextNode(text)

The createTextNode() method creates a Text Node with the specified text.

node.appendChild(node)

The appendChild() method appends a node as the last child of a node.

node.insertBefore(newnode,existingnode)

The insertBefore() method inserts a node as a child, right before an existing child, which you specify.You can also use the insertBefore method to insert/move an existing element (See "More Examples").

node.firstChild

The firstChild property returns the first child node of the specified node, as a Node object.

坑點:返回第一個結點,一般來講都有一個換行,它屬於文本節點,所以firstChild一般會返回文本結點;所以建議用element.firstElementChild

element.firstElementChild

The firstElementChild property returns the first child element of the specified element.

node.removeChild(node)

The removeChild() method removes a specified child node of the specified element.

children和childNodes的區別

element.children

The children property returns a collection of an element's child elements, as an HTMLCollection object.children only contain element nodes.

element.childNodes

The childNodes property returns a collection of a node's child nodes, as a NodeList object.,including text nodes and comment nodes。

 

建立一個結點基本步驟:

建立元素結點 tag【createElement】,建立文本節點text【createTextNode】,添加到元素結點【tag.appendChild】,建立屬性節點 attr【createAttribute

,設置屬性節點值【attr.value = ...】,設置到元素節點【tag.setAttributeNode】;

 

核心DOM就是:節點套節點,孩子找雙親

 

HTML DOM API:

專門用來操做HTML的API

核心DOM是萬能的,若HTML  DOM也沒有想要的API就要本身合理利用二者去編程;

 

練習:

添加,修改,刪除學生信息

table顯示學生信息

點擊學生信息對應行,將學生信息再次顯示在輸入框中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="../../bootstrap-4.3.1-dist/css/bootstrap.min.css">
    <script src="../../bootstrap-4.3.1-dist/js/bootstrap.min.js"></script>
    <script src="../base.js"></script>
    <style>
        .rows{
            cursor: pointer;
        }
    </style>
</head>
<body>
   <div class="container">
       <h1 class="my-5">學生信息登記</h1>
       <form class="form-inline">
            <div class="form-group mr-3">
                    學號:
            </div>
            <div class="form-group">
                <label for="elemt" class="sr-only"></label>
                <input type="text"  class="form-control mr-3" id="id">
            </div>
            <div class="form-group mr-3">
                    姓名:
            </div>
            <div class="form-group">
                <label for="elemt" class="sr-only"></label>
                <input type="text"  class="form-control mr-3" id="name">
            </div>            
            <div class="form-group mr-3">
                    年齡:
            </div>
            <div class="form-group">
                <label for="elemt" class="sr-only"></label>
                <input type="text"  class="form-control mr-3" id="age">
            </div>
            <button id="add" type="button" class="btn btn-primary mr-3" onclick="addStu();" >添加/修改</button>
           </form>
           <hr>
           <h3 class="my-5">學生列表</h1>
    <table class="table table-striped" id="tb">
        <tbody>
                <tr>
                        <th>#</th>
                        <th>學號</th>
                        <th>姓名</th>
                        <th>年齡</th>
                        <th>操做</th>
                    </tr>
        </tbody>
    </table>
   </div>
   <script src="stu_info.js"></script>
</body>
</html>

 

/**
 * Class Page
 */
function Page(){
    this.students = [new Student('3177102326','王有才',21)]; //數組
    this.table = $('tb'); //表格
    this.ipt = document.getElementsByTagName('input');
}


/**
 * Class Student
 * @param {*} stuID 
 * @param {*} stuName 
 * @param {*} stuAge 
 */
function Student(stuID,stuName,stuAge){
        this.id = stuID;
        this.name = stuName;
        this.age = stuAge;
}

/**
 * 添加/更新學生到數組
 */
function addStu(){
        var id = $('id').value;
        var name = $('name').value;
        var age = $('age').value;
        for(var i = 0; i<page.students.length;i++){
            if(page.students[i].id === id){
                page.students[i].name = name;
                page.students[i].age = age;
                vendor(page.students, page.table);
                return;
            }
        }
        page.students.push(new Student(id,name,age));
        vendor(page.students, page.table);
}

/**
 * 刪除位於index下的數組元素
 * @param {*} index 
 */
function delStu(index){
    page.students.splice(index,1);
    vendor(page.students, page.table);
    event.stopPropagation(); //防止冒泡
}


/**
 * 
 * 在index位置上的數組元素的信息填入輸入框中
 * @param {*} index 
 */
function getStuInfo(index){
    $('id').value = page.students[index].id;
    $('name').value = page.students[index].name;
    $('age').value = page.students[index].age;
}


/**
 * 將數組中的學生信息渲染到表格中
 * @param {*} arr 渲染數組
 * @param {*} tb 表格
 */
function vendor(arr,tb){
    var strValue = "";
    if (!arr.length) strValue = '<tr><td colspan="5" class="alert alert-primary" role="alert">nothing to be display</td></tr>'; 
    else{
        arr.forEach(function(item,index){
            strValue
            += '<tr class="rows" onclick="getStuInfo('+index+')"><td>'+ (index+1) +'</td><td>'+item.id+'</td><td>'+item.name+'</td><td>'+item.age+'</td><td><span class="btn btn-danger" onclick="delStu('+index+')">刪除</span></td></tr>'
        });
    }
    tb.getElementsByTagName('tbody')[0].innerHTML = strValue;
}


// /**
//  * 將數組中的學生信息渲染到表格中
//  * 既要添加節點又要添加屬性
//  * 若每一個cell要添加attribute,必須還得緩存一下,會增長代碼量
//  * 單看方便,字符串拼接後使用innerHtml會筆記方便
//  * @param {*} arr 渲染數組
//  * @param {*} tb 表格
//  */
// function vendor(arr, tb){
//     tb.getElementsByTagName('tbody')[0].innerHTML = ""; // 清空原有表格
//     if (!arr.length) {
//         var row = tb.insertRow(-1);
//         row.innerHTML = '<td colspan="5" class="alert alert-primary" role="alert">nothing to be display</td>'
//     }else{
//         arr.forEach(function(item,index){
//             var row = tb.insertRow(-1);  // 坑點:若是table下有thead和tbody,他會插入到thead中
//             row.setAttribute('onclick','getStuInfo('+index+')');
//             row.insertCell(0).innerHTML = index + 1;
//             row.insertCell(1).innerHTML = item.id;
//             row.insertCell(2).innerHTML = item.name;
//             row.insertCell(3).innerHTML = item.age;
//             row.insertCell(4).innerHTML = '<span class="btn btn-danger" onclick="delStu('+index+')">刪除</span>';
//         })
//     }
   
// }


var page = new Page();
/**
 * 每一個input被focus時選中其value
 */
for(var i = 0; i<page.ipt.length;i++){
    page.ipt[i].onclick = function(){
        this.select();
    }
}
vendor(page.students, page.table);

 

function $(id){
    return document.getElementById(id);
}
function print(log){
    console.log(log);
}
function getRandom(start, end){
    if(!(start<=end)) return -1;
    return Math.floor(start + Math.random()*(1 + end - start));
}
相關文章
相關標籤/搜索