web前端練習26----Dom2,節點的 創建添加,刪除,替換,克隆,innerHTML,innerText,顯示隱藏及練習

下面以這個 html 作爲例子 操作:

    <!--節點的 創建添加,刪除,替換,克隆 -->
    <div>這是幾個人</div>
    <ul id="peopleUl" name='ulName'>
        <li id="lip1" type="text">劉備</li>
        <li>關羽</li>
        <li>張飛</li>
    </ul>
    <div>這是幾個動物</div>
    <ul id="animalUl">
        <li id="liA1">豬</li>
        <li>狗</li>
        <li>牛</li>
    </ul>
    <button id="buttonAdd">添加子節點</button></br>
    <button id="buttonChaRu">插入子節點</button></br>
    <button id="buttonDel">刪除子節點</button></br>
    <button id="buttonTiHuan">替換子節點</button></br>
    <button id="buttonKeLong">克隆節點</button></br>
    <button id="buttonInnerHTML">innerHTML</button></br>
    <button id="buttonInnerText">innerText</button></br>

一、添加子節點:

1、添加子節點

創建並添加子節點,是添加到末尾

創建節點

let liNode = document.createElement('li');

添加子節點

ulNode.appendChild(liNode);

        {

            let buttonAdd = document.getElementById('buttonAdd');
            buttonAdd.onclick = function () {
                // 創建一個li節點,並添加文本和屬性
                let liNode = document.createElement('li');
                liNode.innerText = '創建的新節點';
                liNode.type = 'zhh';

                let peopleUl = document.getElementById('peopleUl');
                peopleUl.appendChild(liNode);
            }
        }

2、插入子節點

把給定節點插到子節點的前面

除了插入之外,還有移動功能

把 zhu 插到 liubei 前面

peopleUl.insertBefore(zhu, liubei);

        {
            let buttonChaRu = document.getElementById('buttonChaRu');
            buttonChaRu.onclick = function () {
                // 拿到ul節點
                let peopleUl = document.getElementById('peopleUl');
                // 拿到劉備節點
                let liubei = peopleUl.getElementsByTagName('li')[0];

                // 拿到 豬 的節點
                let zhu = document.getElementById('liA1');
                // 把 zhu 插到 liubei 前面
                peopleUl.insertBefore(zhu, liubei);
            }

        }

二、刪除子節點

ulNode.removeChild(bjNode);

        {
            let buttonDel = document.getElementById('buttonDel');
            buttonDel.onclick = function () {

                // 拿到劉備節點
                let lbNode = document.getElementById('lip1');
                // 拿到劉備節點的父節點
                let ulNode = lbNode.parentElement;
                // 刪除子節點
                ulNode.removeChild(lbNode);
            }
        }

三、替換子節點

replaceChild 把父元素裏面的子節點替換爲另外一個節點

        {
            
            let buttonTiHuan = document.getElementById('buttonTiHuan');
            buttonTiHuan.onclick = function () {

                let zhu = document.getElementById('liA1');
                // 替換
                // 拿到被替換的節點
                let liubei = document.getElementById('lip1');
                // 拿到父節點,把劉備替換成豬
                let liubeiParent = liubei.parentElement;
                liubeiParent.replaceChild(zhu, liubei);
            }
        }

四、克隆節點

Node.cloneNode(true) 方法返回調用該方法的節點的一個副本.

點擊事件克隆不了,要手動賦值

        {
            let buttonKeLong = document.getElementById('buttonKeLong');
            buttonKeLong.onclick = function () {
                let li = document.getElementById('lip1');
                let cloneLi = li.cloneNode(true);
                console.log(cloneLi);
            }

        }

五、innerHTML 和 innerText

對象.innerHTML拿到裏面的子標籤,是一個字符串類型。可以查找,修改,增加,刪除

對象.innerText 拿到標籤裏面的文本,是一個字符串類型。可以查找,可以修改

        {
            let buttonInnerHTML = document.getElementById('buttonInnerHTML');
            buttonInnerHTML.onclick = function() {
                // 對象.innerHTML拿到裏面的子標籤,是一個字符串類型
                // 可以查找,可以修改

                let people = document.getElementById('peopleUl');
                // 查找標籤
                console.log(people.innerHTML);
                // 修改標籤
                people.innerHTML = '<li>豬</li>';
                // 增加標籤
                people.innerHTML = people.innerHTML + '<li>狗</li>';
                // 刪除標籤
                people.innerHTML = '';

            }

            let buttonInnerText = document.getElementById('buttonInnerText');
            buttonInnerText.onclick = function() {
                let people = document.getElementById('peopleUl');
                let zhu = people.getElementsByTagName('li')[0];
                // 對象.innerText 拿到標籤裏面的文本,是一個字符串類型
                // 查找文本
                console.log(zhu.innerText);
                // 修改文本
                zhu.innerText = '狗';

            }

        }

六、元素的顯示隱藏

https://www.cnblogs.com/chenlimei/p/11134358.html

練習

案例1插入節點練習

js自帶的函數中是有 insertBefore();從子元素的前面插入一個元素,沒有從子元素的後面插入的函數,
我們可以自己定義一個insertAfter();從子元素的後面插入一個元素的函數
具體實現如下:

<!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>
</head>

<body>
     <!-- 把給定節點插到子節點的後面 -->
    <ul id="idPeople">
        <li id="liubei">劉備</li>
        <li>關羽</li>
        <li id="zhangfei">張飛</li>
    </ul>

    <ul>
        <li id="idZhu">豬</li>
        <li>狗</li>
        <li>牛</li>
    </ul>
    <button id="charu">插入節點</button>


    <script>
       let charu = document.getElementById('charu');

       charu.onclick = function(){
        let zhu = document.getElementById('idZhu');
        let liubei = document.getElementById('liubei');
        // 把 豬 插到 劉備 的後面
        afterInsterNode(zhu,liubei);

       }
     

        // 自定義把給定節點,插入到子節點的後面
        function afterInsterNode(newNode, selfNode) {
            // 拿到person節點
            let ulPeople = selfNode.parentElement;
            let lis = ulPeople.getElementsByTagName('li');
            //拿到最後一個節點
            let li= lis[(lis.length-1)];
            
            if(selfNode == li){
                ulPeople.appendChild(newNode);
            }else{
                //拿到下一個兄弟節點
                let nextNode= selfNode.nextSibling;
                ulPeople.insertBefore(newNode,nextNode);
            }
            
           

        }


    </script>
</body>

</html>

 

案例2添加刪除子節點的練習

例子:添加員工信息,刪除員工信息
效果圖:

代碼如下:

<!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>
    <style>
        table {
            border: 1px solid black;
            border-collapse: collapse;
            margin-top: 30px;
        }
 
        th {
            border: 1px solid red;
        }
 
        td {
            border: 1px solid blue;
        }
    </style>
 
</head>
 
<body>
    <!-- 添加刪除節點的練習 -->
    <div>員工信息</div>
    姓名:<input type="text" name="姓名" id="idName" placeholder="輸入姓名" value="zhhhhhh">
    郵箱:<input type="text" name="郵箱" id="idEmail" placeholder="輸入郵箱" value="[email protected]">
    工資:<input type="text" name="工資" id="idGongzi" placeholder="輸入工資" value="50000">
    <div><button id="idButton">提交員工信息</button></div>
    <table>
        <tbody id="idTbody">
            <!-- 第一行 -->
            <tr>
                <th>姓名</th>
                <th>郵箱</th>
                <th>工資</th>
                <th></th>
            </tr>
            <!-- 第二行 -->
            <tr>
                <td>zhhhhh</td>
                <td>[email protected]</td>
                <td>50000</td>
                <td><a href="https://www.baidu.com/">刪除</a></td>
            </tr>
            <!-- 第三行 -->
            <tr>
                <td>zhhhhh</td>
                <td>[email protected]</td>
                <td>50000</td>
                <td><a href="https://www.baidu.com/">刪除</a></td>
            </tr>
 
        </tbody>
    </table>
    <script>
        // js 邏輯先拿到三個輸入框的對象
        // 拿到名稱
        let nameEle = document.getElementById('idName');
        // 拿到郵箱
        let emailEle = document.getElementById('idEmail');
        // 拿到工資
        let gongziEle = document.getElementById('idGongzi');
        // 拿到提交按鈕
        let buttonEle = document.getElementById('idButton');
        // 拿到表內容的 idTbody
        let tbodyEle = document.getElementById('idTbody');
 
 
 
 
        // 拿到裏面的值
        buttonEle.onclick = function () {
            let nameValue = nameEle.value;
            let emailValue = emailEle.value;
            let gongziValue = gongziEle.value;
            // 創建tr標籤
            let tr = document.createElement('tr');
            // 創建4個td標籤
            let td1 = document.createElement('td');
            td1.innerText = nameValue;
 
            let td2 = document.createElement('td');
            td2.innerText = emailValue;
 
            let td3 = document.createElement('td');
            td3.innerText = gongziValue;
 
            // 添加一個刪除
            let td4 = document.createElement('td');
            let a = document.createElement('a');
            a.href = 'https://www.baidu.com/';
            a.innerText = '刪除';
            td4.appendChild(a);
 
            tr.appendChild(td1);
            tr.appendChild(td2);
            tr.appendChild(td3);
            tr.appendChild(td4);
 
            tbodyEle.appendChild(tr);
            // 函數調用一下
            deleteRow();
        }
        // 刪除一行
        function deleteRow() {
            // 拿到所有的a鏈接
            let aArray = document.getElementsByTagName('a');
            // 循環 a 獲得點擊設置點擊事件
            for (let i = 0; i < aArray.length; i++) {
                aArray[i].onclick = function () {
                    // 拿到表內容
                    let tbody = this.parentElement.parentElement.parentElement;
                    // 當前點擊的那一行
                    let tr = this.parentElement.parentElement
                                      
                    let shanchu = confirm('真的要刪除嗎'+tr.innerText);
                    if (shanchu) {
                        tbody.removeChild(tr);
                    }
                    // 取消默認行爲,跳轉
                    return false;
                    
                }
            }
        }
 
 
 
 
 
 
 
 
 
    </script>
</body>
 
</html>

   

案例3替換和克隆的練習

寫個例子,節點的互換
點擊北京,北京和中國 兩個節點互換
點擊上海,上海和英國 兩個節點互換
效果圖如下:

<!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>
</head>

<body>
    <!-- 替換節點的練習 -->
    <div>你喜歡那個城市</div>
    <ul id="ulCity">
        <li id="bj">北京</li>
        <li>上海</li>
        <li>廣州</li>
        <li>深圳</li>
    </ul>
    <div>你喜歡那個國家</div>
    <ul id="ulGuoJia">
        <li id="zg">中國</li>
        <li>英國</li>
        <li>德國</li>
        <li>法國</li>
    </ul>
    <script>
        let city = document.getElementById('ulCity');
        let citys = city.getElementsByTagName('li');

        let guojia = document.getElementById('ulGuoJia');
        let guojias = guojia.getElementsByTagName('li');


        for (let i = 0; i < citys.length; i++) {
            citys[i].onclick = function () {
                huhuan(citys[i], guojias[i]);
            }
        }

        for (let j = 0; j < guojias.length; j++) {
            guojias[j].onclick = function () {
                huhuan(citys[j], guojias[j]);
            }

        }


        function huhuan(bj, zg) {
            let chishiUl = bj.parentElement;
            let guojiaUl = zg.parentElement;
            // 克隆城市
            let zg2 = zg.cloneNode(true);
            zg2.onclick = zg.onclick;

            let bj2 = bj.cloneNode(true);
            bj2.onclick = bj.onclick;

            chishiUl.replaceChild(zg2, bj);
            guojiaUl.replaceChild(bj2, zg);

        }



    </script>
</body>

</html>

案例4 左右聯動

選擇左邊的省,右邊對應選擇省的城市

效果圖:

代碼如下:

<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>
</head>

<body>
    <select id="province"></select>
    <select id="city"></select>

    <script>
        // 造一組數據
        let data = [{
            province: '陝西',
            citys: ['西安', '咸陽', '寶雞', '商洛'],
        }, {
            province: '江蘇',
            citys: ['南京', '無錫', '徐州', '常州'],
        }, {
            province: '甘肅',
            citys: ['天水', '白銀', '平涼', '酒泉'],
        }];
        // 拿到節點
        // 拿到省的節點
        let provinceElement = document.getElementById('province');
        // 拿到市的節點
        let cityElement = document.getElementById('city');
        data.forEach(function(value, index) {
            //先把省顯示出來
            let option = document.createElement('option');
            option.innerText = value.province;
            provinceElement.appendChild(option);

            if (value.province == '陝西') {
                // 拿到的省 默認陝西,城市默認陝西的城市
                let cityArray = value.citys;
                cityArray.forEach(function(value, index) {
                    let option = document.createElement('option');
                    option.innerHTML = value;
                    cityElement.appendChild(option);
                });
            }
        });
        // 選擇左邊的省,對應右邊的城市
        provinceElement.onchange = function() {
            let shengValue = provinceElement.options[provinceElement.selectedIndex].value;
            data.forEach(function(value, index) {
                if (value.province == shengValue) {
                    let cityArray = value.citys;
                    cityElement.innerHTML = '';
                    cityArray.forEach(function(value, index) {
                        let option = document.createElement('option');
                        option.innerHTML = value;
                        cityElement.appendChild(option);
                    });


                }

            });

        }
    </script>
</body>

</html>

案例5 購物車全選

全選,取消全選,所有的產品都選擇,全選會選中

效果圖:

代碼如下:

<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>
</head>

<body>

    <label>選擇商品:<input type="checkbox" id="isAll" />全選</label></br>
    <label><input type="checkbox" name="star" /> 衣服</label></br>
    <label><input type="checkbox" name="star" /> 電腦</label></br>
    <label><input type="checkbox" name="star" /> 手機</label></br>
    <label><input type="checkbox" name="star" /> 帽子</label></br>
    <label><input type="checkbox" name="star" /> 襪子</label></br>
    <script>
        let isAllElement = document.getElementById('isAll');
        // 拿到明星的集合
        let starCollection = document.getElementsByName('star');
        let starArray = [...starCollection];
        isAllElement.onclick = function() {
                let isChecked = isAllElement.checked;
                if (isChecked) {
                    // 全選
                    starArray.forEach(function(value, index) {
                        let inputElement = value;
                        inputElement.checked = true;
                    });

                } else {
                    // 全不選
                    starArray.forEach(function(value, index) {
                        let inputElement = value;
                        inputElement.checked = false;
                    });

                }
            }
            // 給明星選擇框加點擊事件
        starArray.forEach(function(value, index) {
            let inputElement = value;
            inputElement.onclick = function() {
                let count = 0;
                starArray.forEach(function(value, index) {
                    if (value.checked) {
                        count++;
                    }
                });

                if (count == starArray.length) {
                    isAllElement.checked = true;
                } else {
                    isAllElement.checked = false;
                }
            }

        });
    </script>
</body>

</html>

案例6 改變圖片練習:

需求:
點擊按鈕切換圖片:

效果圖:

實現思路:
1把圖片路徑放到一個數組中
2設置一個記錄數組下標的變量
3點擊按鈕用數組的不同下標拿到不同的圖片顯示出來

實現代碼如下:

<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">
    <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport">
    <title>Document</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }
        
        .root {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: gold;
        }
    </style>
</head>

<body>
    <div class="root">
        <p style="color:blue;" id="pid">說明</p>
        <img id="image" style="width: 200px; height: 300px;" src="images/1.jpg">
        <span>
            <button id="buttonLast">上一頁</button>
            <button id="buttonNext">下一頁</button>
        </span>
    </div>
    <script>
        // 開始寫js完成圖片切換
        let imgArray = [
            'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3191706504,3660193373&fm=26&gp=0.jpg',
            'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=25834440,1968595786&fm=26&gp=0.jpg',
            'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2179462493,1065615808&fm=26&gp=0.jpg',
            'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1738712335,2051263509&fm=26&gp=0.jpg',
            'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=315442729,2232652672&fm=26&gp=0.jpg'
        ];
        // 圖片節點對象
        let image = document.getElementById('image');
        image.src = imgArray[0];
        // 上一個按鈕對象
        let buttonLast = document.getElementById('buttonLast');
        // 下一個按鈕對象
        let buttonNext = document.getElementById('buttonNext');
        let pid = document.getElementById('pid');
        // 設置上面的標題
        pid.innerText = `一共有${imgArray.length}張,現在是第1張`;
        // 設置一個變量,來記錄數組中的下標
        let index = 0;
        // 上一個按鈕
        buttonLast.onclick = function() {
                index--;
                if (index < 0) {
                    index = imgArray.length - 1;
                }
                image.src = imgArray[index];
                pid.innerText = `一共有${imgArray.length}張,現在是第${index+1}張`;
            }
            // 下一個按鈕
        buttonNext.onclick = function() {
            index++;
            if (index > (imgArray.length - 1)) {
                index = 0;
            }
            image.src = imgArray[index];
            pid.innerText = `一共有${imgArray.length}張,現在是第${index+1}張`;
        }
    </script>



</body>

</html>

 

 

 

 

 

 

 

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