Web前端JavaScript筆記(4)節點

如何獲取元素節點的屬性:

Web前端JavaScript筆記(3)對象中,介紹了訪問行間屬性的方法,除此之外,系統還提供了三個方法訪問元素的屬性:

1. setAttribute: 

2. getAttribute:

3. removeAttribute:

區別:  

1. class屬性的訪問,class與className的區別

2. 行間的自定義屬性,例如在 div中自定義屬性,可以通過getAttribute方法訪問到,但上一節中介紹的方法不支持自定義屬性。

3. setAttribute還可以自定義屬性並且進行賦值,其他的方法不支持。

4. 刪除標籤的屬性,其他方法是沒辦法刪除屬性的,只能將屬性設置爲"",而removeAttribute()可以將屬性刪除。

5. innerHtml   獲取標籤間的內容,會解析文本

6. innerText   獲取標籤間的純文本, 不會解析標籤,設置純文本

7. outerHTML  從外標籤開始到外標籤結束

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let tag = document.getElementById("div1");
            // 訪問行間屬性
            alert(tag.getAttribute("class"));
            alert(tag.getAttribute("title"));
            alert(tag.getAttribute("self"));   // 訪問自定義屬性
            tag.setAttribute("zx", "over");    // 設置自定義的屬性
            tag.removeAttribute("title");

            alert(tag.innerHTML);   // 獲取標籤之間的內容
            alert(tag.innerText);
            alert(tag.outerHTML);
        }

    </script>
</head>
<body>
    <div id="div1" class="box" title="hello" self="me">
        <span>content</span>
    </div>
</body>
</html>

獲取子節點:

系統提供的訪問子節點的方法: (這些子節點共分爲三類)

1. childNodes():訪問當前節點下所有的子節點, 返回對象數組

2. lastChild():訪問當前節點下最後一個子節點

3. firstChild():訪問當前節點下第一個子節點

4. nextSibling:  當前節點的下一個兄弟節點

5. previousSibling:當前節點的上一個兄弟節點

同時,系統爲每個節點提供了三個屬性:

  nodeType nodeName nodeValue
元素節點 1 標籤名 null
屬性節點 2 屬性名 屬性值
文本節點 3 #text 文本內容

當標籤出現換行,縮進的時候,系統也會把換行符,空格當作元素屬性,所以通過childNodes獲取到的元素子結點個數大於實際的子節點個數,可以通過以下的方法來去除這些空白符的影響:

【注】:下面的方法只能獲取子結點中的元素節點

1. children : 只獲取元素節點

2. firstElementChild:

3. lastElementChild:

4. nextElementSibling:

5. previousElementSibling:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let tag = document.getElementById("div1");
            alert(tag.childNodes.length);
            alert(tag.childNodes[0]);
            alert(tag.childNodes[1]);
            alert(tag.childNodes[2]);
            alert(tag.lastChild);

            // 元素屬性:
            alert(tag.childNodes[0].nodeType);
            alert(tag.childNodes[1].nodeType);
            alert(tag.childNodes[2].nodeType);
        }

    </script>
</head>
<body>
    <div id="div1" class="box" title="hello" self="me">  <!--換行的時候會把換行符,空格也會算作元素-->
        <em>content</em>
        節點
        <strong>new node</strong>
    </div>
</body>
</html>

如何獲取元素節點的屬性節點:

系統提供了attributes方法用於獲取元素節點上的所有屬性節點:   獲取到元素的屬性節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let tag = document.getElementById("div1");
            alert(tag.attributes);
            alert(tag.attributes.getNamedItem("title"));
            alert(tag.attributes["title"]);   // 簡便寫法
        }

    </script>
</head>
<body>
    <div id="div1" class="box" title="hello" self="me">  <!--換行的時候會把換行符,空格也會算作元素-->
        節點
    </div>
</body>
</html>

DOM的節點操作:

// document.write()會覆蓋掉原來頁面上的內容

系統提供的節點操作的方法:

1. document.createElement ()  : 創建節點, 參數:標籤名     返回值:創建好的標籤

2. Node.appendChild(node):將某一個節點插入當前節點的子節點內

3. document.createTextNode(文本)  創建文本標籤(純文本,即使有標籤也不會解析)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let tag_div = document.getElementById("div1");
            let tag_btn = document.getElementById("btn1");
            tag_btn.onclick = function () {
                let tag_p = document.createElement("p");    // 創建一個p標籤
                let text_content = document.createTextNode("hello javascript");
                tag_p.appendChild(text_content);
                tag_div.appendChild(tag_p);
            }
        }

    </script>
</head>
<body>
    <div id="div1" class="box">
        <em>This</em>
        節點
        <strong>Content</strong>
    </div>
    <button id="btn1">節點操作</button>
</body>
</html>

每次點擊按鈕,會添加新的文本標籤到div元素中

4. insertBefore() :格式: box1.parentNode.insertBefore(box2, box1);

    功能:將box2添加到box1的前面

5. box1.parentNode.replaceChild(box2, box1);  用box2節點替換box1節點

6. node.cloneNode():克隆出一個新的node節點,返回值就是新創建的node節點, 只克隆節點本身

    node.cloneNode(true):克隆node節點本身以及其所有的子節點

7. box.parent.removeChild(box):刪除box節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let tag_div = document.getElementById("div1");
            let tag_btn = document.getElementById("btn1");
            tag_btn.onclick = function () {
                let tag_p = document.createElement("p");    // 創建一個p標籤
                let text_content = document.createTextNode("hello javascript");
                tag_p.appendChild(text_content);
                document.body.replaceChild(tag_p, tag_div);   // 替換節點
            }
        }

    </script>
</head>
<body>
    <div id="div1" class="box">
        <em>This</em>
        節點
        <strong>Content</strong>
    </div>
    <button id="btn1">節點操作</button>
</body>
</html>

節點操作的案例:

實現在輸入框中輸入內容,點擊添加之後可以添加一條記錄,點擊刪除按鈕可以刪除最後一條記錄,點擊克隆按鈕可以克隆最後一條記錄:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function () {
            let input_tag = $("input_text");
            let bottom_section = $("bottom");
            $("add").onclick = function () {
                let input_content = input_tag.value;
                if(!input_content){
                    alert("請輸入內容");
                }
                else{
                    // 開始創建節點
                    let node = document.createElement("div");
                    let text_node = document.createTextNode(input_content);
                    let btn_node = document.createElement("button");
                    let btn_text_node = document.createTextNode("x");
                    btn_node.appendChild(btn_text_node);
                    node.appendChild(text_node);
                    node.appendChild(btn_node);
                    node.style.background = randomColor();
                    bottom_section.appendChild(node);
                    input_tag.value = "";   // 清空輸入框
                    updateItemsButtons();
                }
            };

            $("delete").onclick = function () {
                let last_node = bottom_section.lastChild;
                bottom_section.removeChild(last_node);
                updateItemsButtons();
            };

            $("clone").onclick = function () {
                let last_node = bottom_section.lastChild;
                let clone_node = last_node.cloneNode(true);   // 深拷貝
                bottom_section.appendChild(clone_node);
                updateItemsButtons();
            };

            function updateItemsButtons() {
                // 對每條記錄上的刪除按鈕綁定函數
                let child_nodes = bottom_section.children;  // 只獲取div元素節點
                let btn_arr = [];
                for(let i=0; i<child_nodes.length; i++)
                {
                    btn_arr.push(child_nodes[i].firstElementChild);
                    //console.log(child_nodes[i].children);
                }
                // 對標籤綁定事件函數
                for (let i=0; i<btn_arr.length; i++)
                {
                    // console.log(btn_arr[i]);
                    btn_arr[i].index = i;
                    btn_arr[i].onclick = function () {
                        bottom_section.removeChild(child_nodes[this.index]);
                    }
                }
            }
        }

    </script>
    <style>
        #container{
            width: 200px;
            border: 1px solid black;
        }
        #top{
            width: 100%;
            height: 30px;
        }
        #top input{
            height: 20px;
            line-height: 30px;
            margin: 0 auto;
        }
        #middle{
            width: 100%;
            height: 50px;
            border: none;
            display: flex;
            flex-direction: row;
            justify-content: space-around;
            background: #0f6674;
        }
        #middle button{
            /*width: 25%;*/
            height: 50%;
            align-self: center;
            /*margin-top: 10px;*/
        }

        #bottom{

        }

        #bottom div{
            height: 25px;
            position: relative;
        }
        #bottom div button{
            position: absolute;
            top: 1px;
            right: 2px;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="top">
            <input type="text" id="input_text" placeholder="請輸入內容">
        </div>
        <div id="middle">
            <button id="add">添加</button>
            <button id="delete">刪除</button>
            <button id="clone">克隆</button>
        </div>
        <div id="bottom">
            <!--<div>content<button>x</button></div>-->
        </div>
    </div>
</body>
</html>

選項卡:

實現選項卡切換的時候,呈現選定狀態的樣式以及下方顯示相對應的內容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function(){
            let btn_arr = $("buttons");
            let buttons = btn_arr.getElementsByTagName("button");
            let content_box = $("content");
            let contents = content_box.getElementsByTagName("div");
            // 爲按鈕添加事件綁定函數
            for (let i=0; i<buttons.length; i++)
            {
                buttons[i].index = i;
                buttons[i].onclick = function () {
                    for (let j=0; j<buttons.length; j++)
                    {
                        buttons[j].className = "";
                        contents[j].style.display = "none";
                    }
                    this.className = "active";
                    contents[this.index].style.display = "block";
                }
            }
        }
    </script>
    <style>
        #container{
            width: 200px;
            height: 300px;
            border: 1px solid black;
        }
        #container #buttons{
            height: 30px;
        }
        #container #content{
            border-top: 1px solid black;
        }
        .active{
            background: #00aa88;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="buttons">
            <button class="active">python</button>
            <button>Java</button>
            <button>C++</button>
        </div>
        <div id="content">
            <div style="display: block">歡迎學習python</div>
            <div style="display: none">歡迎學習Java</div>
            <div style="display: none">歡迎學習C++</div>
        </div>
    </div>
</body>
</html>

offset系列方法-快速獲取當前頁面上的寬,高,距左距離和距右距離:

1. offsetWidth:

2. offsetHeight:

3. offsetLeft:

4. offsetTop:

區別:
通過node.style.width / height獲取的是html盒模型中content的大小

offsetWidth / offsetHeight獲取的是盒模型中content+padding+border的大小

offsetLeft / offsetTop得到的是距離頁面左上角的距離

文檔碎片:

利用文檔碎片可以大幅提高文檔的運行效率:

應用:例如需要在頁面上創建10萬個節點,將10萬個節點全部添加到頁面上

提示: 官方提示的計時器: console.time("hh")    代碼    console.timeEdn();

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script rel="script" src="../JavaScript/tool.js"></script>
    <script>
        window.onload = function(){
            //創建十萬個節點,沒創建一個,插入一個到body中
            console.time("test1");
            for (let i=0; i<100000; i++)
            {
                let new_tag = document.createElement("div");
                document.body.appendChild(new_tag);
            }
            console.timeEnd("test1");     // 官方提供的計時器

            // // 先創建所有節點,在插入節點
            console.time("test2");
            let node = document.createElement("div");    // 先創建一個標籤
            for (let i=0; i<100000; i++)
            {
                let new_node = document.createElement("div");
                node.appendChild(new_node);
            }
            document.body.appendChild(node);
            console.timeEnd("test2");     // 官方提供的計時器
        }
    </script>
</head>
<body>

</body>
</html>

第二種方法插入節點的速度更快,稱之爲文檔碎片操作。

數組元素的遍歷方法:

1. for循環

2. for-in

3. for-each方法:

<script>
        window.onload = function(){
            let arr = [1,4,2,3,4,2];
            for (let i=0; i<arr.length; i++)
            {
                console.log(i);
            }

            for(let elem in arr){
                console.log(elem);
            }

            arr.forEach(function (item, index, arr) {
                console.log(item);
            })
        }
</script>

------------------------------------------------------------------------------------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章