1. 程式人生 > >JavaScript學習筆記(三)

JavaScript學習筆記(三)

第一個 nis 學習筆記 app 用戶 users change cor rev

本課程對應的視頻地址:http://edu.51cto.com/course/15019.html

1、DOM

DOM:Document Object Model

技術分享圖片

1.1、W3C規定的三類DOM標準接口

Core DOM(核心DOM),適用於各種結構化文檔

XML DOM,專用於XML文檔

HTML DOM,專用於HTML文檔(了解)

1.2、Core DOM

1.2.1、查找dom

document.getElementById("id"):根據id元素來查找某個對象

document.getElementsByTagName("tag"):根據標簽來獲取元素-->數組

document.getElementsByName("name"):根據name來獲取元素-->數組

nextElementSibling:下一個元素節點
previousElementSibling:上一個元素節點
childNode:子節點(包含文本節點)
children:子元素節點
childElementCount:子元素的數量
lastElementChild:最後一個元素節點
firstElementChild:第一個元素節點
firstChild:第一個節點
lastChild:最後一個節點
nodeType:節點的類型
    元素節點:1
    屬性節點:2
    文本節點:3
parentNode:父節點

案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function changeImg(){
            var imgObject = document.getElementById("myimg");
            imgObject.src="../images/2.jpg";
        }
        function getData(){
            var seasons = document.getElementsByName("season");
            var str= "";
            for(var i = 0 ;i<seasons.length;i++) {
                str=str+seasons[i].value+"<br/>";
            }
            document.getElementById("result").innerHTML=str;
        }
        function getInputData(){
            var inputs = document.getElementsByTagName("input");
            var str= "";
            for(var i = 0 ;i<inputs.length;i++) {
                str=str+inputs[i].value+"<br/>";
            }
            document.getElementById("result").innerHTML=str;
        }
    </script>
</head>
<body>
    <img src = "../images/1.jpg" id = "myimg"/>
    <input type="button" value="修改圖片" onclick="changeImg()"/>

    <input type="text" value="春" name="season"/>
    <input type="text" value="夏" name="season"/>
    <input type="text" value="秋" name="season"/>
    <input type="text" value="東" name="season"/>
    <input type="button" value="得到季節" onclick="getData()"/>
    <input type="button" value="獲取所有的input標簽的內容" onclick="getInputData()"/>
    <div id = "result">

    </div>
</body>
</html>

也可以通過setAttribute(attr,value)設置對象的屬性

imgObject.setAttribute("src","../images/2.jpg");
imgObject.setAttribute("onclick","myFun()");

那麽如果想獲取屬性的值,就可以通過getAttribute("name")來獲取

如果我們想對對象加樣式,通過object.style屬性操作

  <script type="text/javascript">
        window.onload = function(){
            var box = document.getElementById("box");
            box.style.border="1px solid red";
            box.style.backgroundColor="#ccc";
            box.style.width="300px";
            box.style.height="300px";
        }
    </script>

1.2.2、dom的創建相關操作

案例:

<script type="text/javascript">
        window.onload = function(){
            var div = document.createElement("div");
            div.style.width="400px";
            div.style.height="400px";
            div.style.border="1px solid red";
            document.body.appendChild(div);
            var input = document.createElement("input") ;
            input.setAttribute("type","text");
            input.setAttribute("value","zhangsan");
            div.appendChild(input);
        }
    </script>

與dom相關操作有哪些呢?

createElement:創建一個元素節點

appendChild:將這個元素加入某個元素內部

insertBefore(在某個節點前面插入新的節點):parentElement.insertBefore(newNode,thisNode)

cloneNode:克隆,有一個參數,默認是false,當為true表示深克隆(連同子節點一起克隆)

案例2:插入兄弟節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        window.onload=function (ev) {
            var cc = document.getElementById("cc");
            var li = document.createElement("li");
            li.innerHTML="貂蟬";
            //insertBefore(newNode,已經存在的節點)
            document.body.insertBefore(li,cc);
        }

    </script>
</head>
<body>
    <li>關羽</li>
    <li id="cc">曹操</li>
    <li>狂鐵</li>
</body>
</html>

案例3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function copy(){
            var img = document.getElementById("id01");
            var newImg = img.cloneNode();
            document.body.insertBefore(newImg,img);
        }
        function copyul(){
            var myul = document.getElementById("myul");
            document.body.appendChild(myul.cloneNode(true));
        }

    </script>
</head>
<body>
    <img id = "id01" src = "../images/1.jpg"/>
    <input type="button" onclick="copy()" value="復制"/>
    <ul id="myul">
        <li>關羽</li>
        <li>盾山</li>
    </ul>
    <input type="button" onclick="copyul()" value="復制ul"/>

</body>
</html>

1.2.3、刪除和替換操作

removeChild:刪除某個子節點

replaceChild(new,old):新的替換舊的節點

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function myremove(){
            var img = document.getElementById("id02");
            document.body.removeChild(img);
        }
        function myreplace(){
            var img = document.getElementById("id01");
            var newImg = document.createElement("img");
            newImg.setAttribute("src","../images/5.jpg");
            document.body.replaceChild(newImg,img);
        }
    </script>
</head>
<body>
<img id = "id01" src = "../images/1.jpg"/>
<img id = "id02" src = "../images/2.jpg"/>
<img id = "id03" src = "../images/3.jpg"/>
<input type="button" onclick="myremove()" value="移除"/>
<input type="button" onclick="myreplace()" value="替換操作"/>
</body>
</html>

1.3、練習

1.3.1、隔行變色

<script type="text/javascript">
            window.onload=function(){
                var trs = document.getElementsByTagName("tr");
                for(var i = 0 ;i<trs.length;i++) {
                    if(i%2==0) {
                        trs[i].style.backgroundColor="#ccc";
                    }
                }
            }
    </script>

高亮顯示

 <script type="text/javascript">
            window.onload=function(){
                var trs = document.getElementsByTagName("tr");
                //onmouseover :鼠標經過
                //onmouseout:鼠標離開
                for(var i = 0 ;i<trs.length;i++) {
                    trs[i].onmouseover=function(){
                        this.style.backgroundColor=‘#ccc‘;
                    };
                    trs[i].onmouseout=function(){
                        this.style.backgroundColor=‘white‘;
                    }

                }
            }
    </script>

1.3.2、實現全選,反選等效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript">
        window.onload=function(){
            var allObject = document.getElementById("all");
            var allHobbies = document.getElementsByName("hobby");
            //全選效果
            allObject.onclick=function(){
                for(var i = 0 ;i<allHobbies.length;i++) {
                    allHobbies[i].checked=this.checked;
                }
            }
            for(var i = 0;i<allHobbies.length;i++) {

                allHobbies[i].onclick=function(){
                   allObject.checked=checkAll();
                }
            }
            var fanObject = document.getElementById("fan");
            fanObject.onclick=function(){
                for(var i = 0;i<allHobbies.length;i++) {
                    allHobbies[i].checked=!allHobbies[i].checked;
                }
                //判斷是否全部選中
                allObject.checked=checkAll();
            }
        }

        function checkAll(){
            var allHobbies = document.getElementsByName("hobby");
            var flag = true;
            for(var i = 0;i<allHobbies.length;i++) {
                if(allHobbies[i].checked==false){
                    flag=false;
                    break;
                }
            }
            return flag ;
        }
    </script>
</head>
<body>
<input type="checkbox" id="all"/>全選 <input type="checkbox" id="fan"/>反選<br/>
<hr/>
<input type="checkbox" name="hobby">關羽<br/>
<input type="checkbox" name="hobby">曹操<br/>
<input type="checkbox" name="hobby">貂蟬<br/>
</body>
</html>

1.3.3、動態編寫一個表格

技術分享圖片

案例實現:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        var table ;
        var thead ;
        var tbody;
        window.onload = function(){
            createTable();
            createTheadData();
            createTbodyData();
        }

        function createTable(){
            table  = document.createElement("table");
            //將table加入到body中
            document.body.appendChild(table);
            thead  = document.createElement("thead");
            //將thead加入了table中
            table.appendChild(thead);
            tbody = document.createElement("tbody");
            table.appendChild(tbody);

            //為table元素添加相關關屬性
            table.setAttribute("border","1");
            table.setAttribute("width","100%");
        }
        function createTheadData(){
            //向thead中插入了一行
            var tr = thead.insertRow();
            //tr我需要添加單元格
            var td_id = tr.insertCell();
            td_id.innerHTML="編號";
            var td_name = tr.insertCell();
            td_name.innerHTML="姓名";
            var td_oper = tr.insertCell();
            td_oper.innerHTML="數據操作";
        }
        //生成10條數據
        function createTbodyData(){
            for(var i = 0 ;i<10;i++) {
                var tr = tbody.insertRow();
                var td_id = tr.insertCell();
                td_id.innerHTML=i;
                var td_name = tr.insertCell();
                td_name.innerHTML="張"+i;
                var td_oper = tr.insertCell();
                td_oper.innerHTML=‘<input type="button" onclick="mydelete(this)" value = "刪除"/><input type="button" onclick="updatePre(this)" value = "修改"/>‘;
            }
        }
        function mydelete(obj) {
            if(confirm(‘確定刪除此行嗎‘)) {
                var tr = obj.parentNode.parentNode;
                var rowIndex = tr.rowIndex-1;
                tbody.deleteRow(rowIndex);
            }
        }
        /*
        *   需要將數據區改為可編輯狀態(input)
        *   按鈕部分變成確定和取消
        * */
        function updatePre(obj) {
            var td = obj.parentNode ;
            var td_name = td.previousElementSibling;
            var td_id = td.previousElementSibling.previousElementSibling;
            var id = td_id.innerHTML;
            var name = td_name.innerHTML;
            //在js中可以為對象動態添加屬性
            td_name.tag=name;
            td_id.tag=id;
            td_name.innerHTML="<input type=‘text‘ value=‘"+name+"‘/>";
            td_id.innerHTML="<input type=‘text‘ value = ‘"+id+"‘/>";

            //改變數據操作區的按鈕
            var btn_confirm = document.createElement("input");
            btn_confirm.setAttribute("type","button");
            btn_confirm.setAttribute("value","確定");
            btn_confirm.setAttribute("onclick","confirmData(this)");
            var btn_cancel = document.createElement("input");
            btn_cancel.setAttribute("type","button");
            btn_cancel.setAttribute("value","取消");
            btn_cancel.setAttribute("onclick","myCancel(this)")
            td.innerHTML="" ;
            td.appendChild(btn_confirm);
            td.appendChild(btn_cancel);
        }

        function myCancel(obj){
            var td = obj.parentNode ;
            var td_name = td.previousElementSibling;
            var td_id = td.previousElementSibling.previousElementSibling;
            td_id.innerHTML=td_id.tag;
            td_name.innerHTML=td_name.tag;
            //還原最後一個td
            td.innerHTML=‘<input type="button" onclick="mydelete(this)" value = "刪除"/><input type="button" onclick="updatePre(this)" value = "修改"/>‘;
        }
        /*
          id,name必須要非空
        * id不能重復
        * */
        function confirmData(obj) {
            //確定
            var td = obj.parentNode ;
            var td_name = td.previousElementSibling;
            var td_id = td.previousElementSibling.previousElementSibling;
            //首先獲取用戶輸入的值
            var name  = td_name.getElementsByTagName("input")[0].value;
            var id  = td_id.getElementsByTagName("input")[0].value;
            if(name==""||id=="") {
                alert("對不起,數據不能為空");
                return ;
            }
            //判斷ID不能重復
            if(isSame(id)) {
                alert("對不起,id不能重復");
                return  ;
            }

            //驗證都通過了,那麽接下來就是將數據真正的放在單元格中
            td_name.innerHTML=name;
            td_id.innerHTML=id;
            td.innerHTML=‘<input type="button" onclick="mydelete(this)" value = "刪除"/><input type="button" onclick="updatePre(this)" value = "修改"/>‘;

        }

        function isSame(id){
            var flag = false;
            for(var i = 0 ;i<tbody.rows.length;i++) {
                var tr = tbody.rows[i];
                if(id==tr.firstElementChild.innerHTML) {
                    flag = true
                    break;
                }
            }
            return flag ;
        }

    </script>
</head>
<body>
</body>
</html>

總結:

table對象:

? rows屬性

? insertRow():插入一行

? deleteRow():刪除一行

tableRow對象:行對象

? cells:單元格對象

? rowIndex:行號

? insertCell():插入單元格

? deleteCell():刪除單元格

TableCell對象:每個單元格

? cellIndex:單元格的索引

JavaScript學習筆記(三)