day5_javascript3

day5_javascript3

1DOM树结构

html节点结构

image-20250730100041460

其他还有文本节点 #text 注释节点

2查找元素

    /*
    查找元素的函数
        getElementById  通过id查找元素  html标签
                        返回指定id的第一个元素
                        id值不要重复 不然容易获取不到
        getElementsByClassName 通过class值 找元素 获得元素集合
                        想控制元素的属性时  需要先取到元素再操作 经常搭配遍历使用

        getElementsByTagName   通过标签名 找元素  获得元素集合
                        想控制元素的属性时  需要先取到元素再操作 经常搭配遍历使用   
    
    
    */
   /*
   查找元素的属性
   
   通过节点关系查找的属性
    子节点
    children           所有子元素
    firstElementChild  第一个子元素
    lastElementChild   最后一个子元素

    兄弟节点(同级节点)
    nextElementSibling     下一个兄弟
    previousElementSibling 上一个兄弟
    
    父节点
    parentElement          父节点


    Prototype 原型
    HTMLCollection   元素集合(使用这个)
    NodeList         节点集合



   */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul id="myUl">
        <li>新闻1</li>
        <li>新闻2</li>
        <li id="myli">新闻3</li>
        <li>新闻4</li>
        <li>新闻5</li>
    </ul>
</body>
<script>
    
    /*
    查找元素的函数
        getElementById  通过id查找元素  html标签
                        返回指定id的第一个元素
                        id值不要重复 不然容易获取不到
        getElementsByClassName 通过class值 找元素 获得元素集合
                        想控制元素的属性时  需要先取到元素再操作 经常搭配遍历使用

        getElementsByTagName   通过标签名 找元素  获得元素集合
                        想控制元素的属性时  需要先取到元素再操作 经常搭配遍历使用   
    
    
    */
   /*
   查找元素的属性
   
   通过节点关系查找的属性
    子节点
    children           所有子元素
    firstElementChild  第一个子元素
    lastElementChild   最后一个子元素

    兄弟节点(同级节点)
    nextElementSibling     下一个兄弟
    previousElementSibling 上一个兄弟
    
    父节点
    parentElement          父节点


    Prototype 原型
    HTMLCollection   元素集合(使用这个)
    NodeList         节点集合



   */


   console.log(document.getElementById("myUl").children);
   console.log(document.getElementById("myUl").childNodes);
   console.log(document.getElementById("myUl").firstElementChild);
    console.log(document.getElementById("myUl").lastElementChild);

    console.log(document.getElementById("myli").nextElementSibling.nextElementSibling.previousElementSibling.previousElementSibling)
    console.log(document.getElementById("myli").parentElement.parentElement)
</script>
</html>

2操作属性

属性方式操作属性

元素.属性

写 元素.属性 = 新值

读 元素.属性

函数方式操作属性

元素.setAttribute('属性名','属性值')

元素.getAttribute('属性名')

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="myText" type="text"/>
</body>
<script>
    //选择一套使用 尽量不要穿插使用


   //document.getElementById("myText").value = "jack"
    //通过工具编写时使用
   //document.getElementById("myText").setAttribute('value','rose')
</script>
</html>

3动态dom操作

    /*
    (了解)
    创建元素
    document.createElement("li")  创建完一般还要设置属性

    追加子元素
    document.getElementById("myUl").appendChild(newLi)

    指定在某个元素前
    document.getElementById("myUl").insertBefore(newLi,document.getElementById("myLi"))

    复制元素
    document.getElementById("myLi").cloneNode(true)  bol决定是否复制子元素 默认false
    
    删除指定的子元素
    document.getElementById("myUl").removeChild(document.getElementById("myUl").lastElementChild)
    
    */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="addEle()">新增</button>
    <button onclick="addEle2()">新增2</button>
    <button onclick="addEle3()">新增3</button>
    <button onclick="delEle()">删除</button>
    <ul id="myUl">
        <li id="myLi"><button>测试按钮</button></li>
    </ul>
</body>
<script>

    /*
    (了解)
    创建元素
    document.createElement("li")  创建完一般还要设置属性

    追加子元素
    document.getElementById("myUl").appendChild(newLi)

    指定在某个元素前
    document.getElementById("myUl").insertBefore(newLi,document.getElementById("myLi"))

    复制元素
    document.getElementById("myLi").cloneNode(true)  bol决定是否复制子元素 默认false
    
    删除指定的子元素
    document.getElementById("myUl").removeChild(document.getElementById("myUl").lastElementChild)
    
    */


    function addEle(){

        //生成了临时元素
        //虚拟dom元素 支持所有dom操作 但是不会显示
        let newLi = document.createElement("li")
        // let newButton = document.createElement("button")
        // newButton.innerHTML="新按钮"
        // newLi.appendChild(newButton)

        //简化dom操作的方式
        newLi.innerHTML = "<button style='color:red;'>新按钮</button>"

        //挂到dom树上
        document.getElementById("myUl").appendChild(newLi)

        //document.getElementById("myUl").lastElementChild.innerHTML = "新元素"

    }

    function addEle2(){
        let newLi = document.createElement("li")
        newLi.innerHTML = "<button style='color:red;'>新按钮</button>"

        //挂到dom树上
        document.getElementById("myUl").insertBefore(newLi,document.getElementById("myLi"))

    }

    function addEle3(){
        //复制节点 bol管是否复制子节点
        let newLi = document.getElementById("myLi").cloneNode(true)

        document.getElementById("myUl").appendChild(newLi)
    }

    function delEle(){
        document.getElementById("myUl").removeChild(document.getElementById("myUl").lastElementChild)
    }

</script>
</html>

注意:

dom操作时 两个步骤

1建立虚拟dom 虚拟dom拥有完整的dom结构 可以做dom操作

2挂载到dom树上

4简化dom操作

innerHTML属性 可以让浏览器解析html标签 利用这个特性 可以简化dom操作的替换功能 和追加功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="addEle()">新增</button>
    <button onclick="delEle()">删除</button>
    <ul id="myUl">
        <li id="myLi"><button>测试按钮</button></li>
        
    </ul>
</body>
<script>
    /*
    使用innerHTML 替换  追加 
    删除不方便 使用原生js
    
    */

    function delEle(){
        document.getElementById("myUl").removeChild(document.getElementById("myUl").lastElementChild)
    }


    function addEle(){
        //console.log(document.getElementById("myUl").innerHTML);
         let newEleStr = `<li><input type="text" value="新输入框" /></li>`
         document.getElementById("myUl").innerHTML+= newEleStr


    }


</script>
</html>

5table动态操作

js中吧table描述为二维数组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="addRow()">新增</button>
    <button onclick="delRow()">删除</button>
    <button onclick="addRow2()">简化新增</button>
    <button onclick="addRow3()">加载数据</button>
    <table id="myTable" border="1">

        <caption>人员信息表</caption>
        <thead>
            <tr>
                <!-- 单元格 -->
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>住址</th>
            </tr>
        </thead>


        <!-- 行 -->
         <tbody id="mainData">

        
        </tbody>


    </table>
    
</body>
<script>
    /*
    rows  行
    cells 单元格

        insertRow(1)        添加tr
        insertCell(0)       添加td
        deleteRow(行索引)    删除tr
    
    */
    //console.log(document.getElementById("myTable").rows[2].cells[1].innerHTML);
     

    let userData = [[1,'jack',15,'车里'],[2,'rose',25,'车里'],[2,'rose老公',25,'车底']]

    function addRow(){
       let newTr = document.getElementById("myTable").insertRow(1)
       let td0 = newTr.insertCell(0)
       let td1 = newTr.insertCell(1)
       let td2 = newTr.insertCell(2)
       let td3 = newTr.insertCell(3)

       td1.innerHTML = "test"
        td2.innerHTML = "test2"
    }

    function delRow(){
        document.getElementById("myTable").deleteRow(document.getElementById("myTable").rows.length-1)
    }

    //简化dom操作
    function addRow2(){
        let myContent = `
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                </tr>
        `
        document.getElementById("mainData").innerHTML+=myContent
    }

    function addRow3(){
        for(let user of userData){
            let myContent = `
                <tr>
                    <td>${user[0]}</td>
                    <td>${user[1]}</td>
                    <td>${user[2]}</td>
                    <td>${user[3]}</td>
                </tr>
            `
            document.getElementById("mainData").innerHTML+=myContent
        }
    }
</script>
</html>

6js常用对象

6.1String

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>

    /*
    字符串处理
    与java中的方法大同小异
    不分字符和字符串 单字符可以使用 多字符也可以使用
    
    */

    let myStr = "abc1DB23321";

    console.log(myStr.charAt(2));
    console.log(myStr.indexOf("c"));
    console.log(myStr.substring(2,4));//起始  结束
    console.log(myStr.substr(2,4));   //起始  个数
    console.log(myStr.toUpperCase()); // 转大写 忽略大小写时 可以用这个处理之后再匹配
    console.log(myStr.toLowerCase()); // 转小写

    let myStr2 = "name=jack";
    console.log(myStr2.split("="));   //解析和处理有格式的字符串时使用
    console.log(myStr2.split("=")[1]);

    console.log(myStr2.startsWith("age")); //字符串匹配开头
    console.log(myStr2.endsWith("ok"));    //字符串匹配结尾

    console.log(myStr2.replace("jack","rose"));

</script>
</html>

6.2Math对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    let myNum = 10.5;

    console.log(Math.floor(myNum)); //向下取整
    console.log(Math.ceil(myNum));  //向上取整
    console.log(Math.round(myNum)); //四舍五入
    console.log(Math.abs(1-3));     //绝对值 经常用来得到两个数之间相差的值

    //随机数的获取方式
    console.log(parseInt(Math.random()*3)+5 );   //[0-1)  比取的值多乘一个数 向下取整
    //[2,5,8,9]  随机数生成索引 获取数据



</script>


</html>

6.3Date对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.30.1/moment.min.js"></script>
</head>
<body>
    
</body>
<script>
    //获取当前日期
    console.log(new Date());                     //当前时间点
    console.log(new Date('1999/11/11 11:11:11'));//指定日期格式 用字符串
    console.log(new Date('1999-11-11 11:11:11'));
    console.log(new Date(872736464665));         //指定毫秒数 得到日期对象
      
    //把日期参数节点获取出来 再自己拼接
    let nowDate = new Date();
    console.log(nowDate.getFullYear());
    console.log(nowDate.getMonth()+1);
    console.log(nowDate.getDate());
    console.log(nowDate.getDay());
    console.log(nowDate.getHours());
    console.log(nowDate.getMinutes());
    console.log(nowDate.getSeconds());

    //nowDate.getTime() 通过毫秒数计算时间
    console.log(new Date(nowDate.getTime()+60*60*24*3*1000));   


    console.log(moment().format('YYYY-MM-DD, h:mm:ss a'));

</script>
</html>

6.4Array对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul id="myUl">
        <li>aaaa</li>
        <li>bbb</li>
        <li>ccc</li>
    </ul>

</body>
<script>
    /*
    js中的数组 不是其他编程语言里的数组

    没有泛型的ArrayList
    可以随意扩容  什么数据都可以放
    
    */

    let myArr = new Array()
    let myArr2 = [13,"a",true,new Date(),[1,2,3]]
    console.log(myArr);
    console.log(myArr2);

    let myArr3 = [3,1,5,4,7,6]
    console.log(myArr3.join(','));//按指定的字符 转成字符串
    console.log(myArr3.sort(function(a,b){return a-b}));//排序 升序 降序

    //队头操作 队尾操作
    myArr3.unshift('b')  //队头添加
    myArr3.shift()       //队头删除
    myArr3.push('a')     //队尾添加
    myArr3.pop()         //队尾删除

    console.log(myArr3);
    //动态操作元素的方法
    //myArr3[2] = null
    //            起始索引 处理个数  可以选参数替换为xxx
    myArr3.splice(2,3,'a','b','c')

    console.log(myArr3);
    console.log("------------------");
    //遍历Array 数组
    myArr3.forEach((data)=>{
        console.log(data);
    })


    let eles = document.getElementById("myUl").children
    console.log(eles);
    let newEle = Array.from(eles)
    console.log(newEle);
    newEle.forEach((data)=>{
        console.log(data);
    })
</script>
</html>

6.5JSON对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
    /*
    json  js对象标签  js中做自定义对象

    {"key":value}

    key     固定字符串
    value   可以任意类型 数字 字符串 bol值 对象 数组 函数 都支持

    两种写法
    标准json   "key"      与字符串互换时 必须使用标准json
    简化json    key       不与后端交互数据时 只在网页中使用时

    JSON.parse(jsonObj1)       字符串转json 只支持标准格式  简化格式会报错
    JSON.stringify(jsonObj1)   josn转字符串 转成标准json格式字符串

    经常与数组搭配使用



    */
    let newObj = {"name":"jack",
                  "age":15,
                  study(){
                    console.log(this.name+"我在学习");
                    }
                }
    newObj.age = 25
    newObj.addr = "科学大道15号"
    console.log(newObj);
    newObj.study()

    // let jsonObj1 = `{"name":"rose","age":15}`;
    // let jsonObj2 = `{name:"rose",age:15}`;
    // console.log(jsonObj1,jsonObj2);
    // console.log(JSON.parse(jsonObj1)         );
    // console.log(JSON.parse(jsonObj2)         );

    let jsonObj1 = {"name":"rose","age":15};
    let jsonObj2 = {name:"rose",age:15};
    
    console.log(JSON.stringify(jsonObj1),JSON.stringify(jsonObj2));
    console.log("---------------------");

    let students = [{name:"rose",age:15},{name:"jack",age:15},{name:"abc",age:15}]
    console.log(students[2].name);

    let classInfo = {cName:'终极1班',cAddr:'铃兰高中',stus:[{name:"蔡徐坤",age:15},{name:"谢广坤",age:15},{name:"谢顶坤",age:16}]}            

    console.log(classInfo.stus[2].name);  


    //json取值的第二种语法    
    console.log(jsonObj2['name']   );
          

</script>
</html>
posted @ 2025-07-30 21:33  小胡coding  阅读(5)  评论(0)    收藏  举报