什么是 DOM?

DOM是 Document Object Model(文档对象模型)的缩写

DOM是 W3C(万维网联盟)的标准。

DOM 定义了访问 HTML 和 XML 文档的标准:

“W3C 文档对象模型 (DOM) 是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容、结构和样式。”

W3C DOM 标准被分为 3 个不同的部分:

  • 核心 DOM - 针对任何结构化文档的标准模型,无论是XML,HTML以及其它的标记语言都是通用的
  • XML DOM - 针对 XML 文档的标准模型
  • HTML DOM - 针对 HTML 文档的标准模型

什么是 HTML DOM?

HTML DOM 是:

  • HTML 的标准对象模型
  • HTML 的标准编程接口
  • W3C 标准

HTML DOM 定义了所有 HTML 元素的对象和属性,以及访问它们的方法。

换言之,HTML DOM 是关于如何获取、修改、添加或删除 HTML 元素的标准。

区别

对于核心DOM,  API简单,原理简单,编码复杂;

HTML DOM,API复杂,编程形象化,编码轻松

对于核心DOM只有标记语言的概念,并不认识各个标签的含义,标记语言是由节点互相嵌套而成;

  • 元素结点
  • 属性节点
  • 文本节点
  • 注释结点

核心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));
}