js基础知识





变量

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 单行注释

        /*
        多行注释
        多行注释
        多行注释
        */

        // 变量
        let x;              // JS需要声明一个变量以后才能赋值,或者 let x = 10
        x = 10;             // 变量赋值
        console.log(x);     // 浏览器控制台打印

        // 一行可以声明多个变量
        let name="tom",number=456;
        console.log(name, number);
    </script>

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




数据类型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        number     -----  数值
        boolean    -----  布尔值
        string     -----  字符串
        undefined  -----  undefined
        null       -----  null
         */

        // number数据类型下有无数个值
        let s1 = 123;
        let s2 = 3.14;
        console.log(typeof s1);  // 查看数据类型
        console.log(typeof s2);

        // boolean  数据类型下只有 false true 两个值
        let b1 = true;
        let b2 = false;
        console.log(typeof b1);
        console.log(typeof b2);

        // string  数据类型下有无数个值
        let t1 = 'hello';
        console.log(typeof t1);

        // undefined  数据类型下只有 undefinde
        // 1 变量只声明未赋值  
        // 2 函数无返回值 都是undefinde
        let u1;
        console.log(u1);         // u1 这个变量声明了,但是未赋值,是值 undefined
        console.log(typeof u1);  // 这个是u1这个变量的类型 undefined 。常见的变量类型有number boolean string等

        // null  为对象预留出来的一块空间
        let n1;
        n1 = null;
        console.log(n1);         // null
        console.log(typeof n1);  // object
    </script>
</head>
<body>
</body>
</html>




运算符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 运算符
        /*
            算术运算符:
                +   -    *    /     %       ++     --

            比较运算符:
                >   >=   <    <=    !=    ==    ===   !==

            逻辑运算符:
               &&    ||    !
               and   or   not  -- 相当于python的and or not

            赋值运算符:
                =  +=   -=  *=   /=

            字符串运算符:
                +  连接,两边操作数有一个或两个是字符串就做连接运算
        */

        let i = 100;
        // i+=1;  // i=i+1
        // i++;   // 等价于 i=i+1
        ++i;      // 等价与 i=i+1
        console.log('i', i);  // 101

        let i2=100;
        y1=++i2;  // i2自己先加1,然后赋值给y1
        console.log('i2', i2);  // 101
        console.log('y1', y1);  // 101

        let i3=100;
        y2=i3++;  // 先把i3 赋值给y,然后i3自己在加1
        console.log('i3', i3);  // 101
        console.log('y2', y2);  // 100

        // 全等于 === 要类型和值都相等才返回true
        console.log(123==='123');  // false

        // 等于 ==
        console.log(123=='123');   // true
        console.log(1234=='123');  // false
        // 类型转化 . JS在判断两个值相等的时候,如果不相等,会转化成字符串在比较一下,如果这时候相等,就返回true
    </script>
</head>
<body>
</body>
</html>




流程控制语句

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // js的流程控制语句
        /*
            if (表达式){
                       语句1;
                       ......
                       }
             else{
                       语句2;
                       .....
                       }
         */


        // 判断语句
        // if ... else if ... else
        let score = 5;
        if (score > 90) {
            console.log('优秀');
        } else if (score > 80) {
            console.log('良好');
        } else {
            console.log('一般');
        }

        // switch ... case ... break
        let x = 1;
        switch (x) {
            case 1:
                console.log('星期1');
                break;
            case 2:
                console.log('星期2');
                break;
            case 3:
                console.log('星期3');
                break;
            case 4:
                console.log('星期4');
                break;
            case 5:
                console.log('星期5');
                break;
            case 6:
                console.log('星期6');
                break;
            case 7:
                console.log('星期7');
                break;
            default:
                console.log('非法输入');
                break;
        }

        // 循环语句 迭代循环 条件循环
        // while
        let n = 0;
        while (n < 5) {
            console.log(n);
            n++;
        }

        // for 在js中,for循环也属于条件循环
        for (let z = 0; z < 5; z++) {
            console.log(z);
        }
    </script>
</head>
<body>
</body>
</html>




异常处理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        /*
        try {
            // 这段代码从上往下运行,其中任何一个语句抛出异常该代码块就结束运行
        }
        catch (e) {
            // 如果try代码块中抛出了异常,catch代码块就会被执行
            // e 是一个局部变量,用来指向error对象或者其他抛出的异常
        }
        finally {
            // 无所怎样,这块代码最后都会被执行
        }
         */

        try {
            console.log('a');
            console.lo('b');
            console.log('c');
            console.log('d');
        } catch (e) {
            console.log(e);
            console.log('eeee');
        } finally {
            console.log('end');
        }
    </script>
</head>
<body>
</body>
</html>




字符串对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 字符串对象

        // 创建字符串的方式
        let s1 = ' Alnk ';
        // let s2 = new String('tom');
        console.log(s1);
        // console.log(s2);

        // 获取字符串的长度
        console.log(s1.length);  // 6 空格也算

        // 转为小写
        console.log(s1.toLowerCase());

        // 转为大写
        console.log(s1.toUpperCase());

        // 去除字符串两边空格
        console.log(s1.trim());

        // 获取指定位置字符 其中2为要获取的字符索引
        console.log(s1.charAt(2));

        // 查询字符串位置,返回的是索引 从索引1的地方开始查找
        console.log('====')
        console.log(s1.indexOf('e',4));  // 5
        console.log(s1.indexOf('e'));    // 3
        // 反向查找
        console.log(s1.lastIndexOf('e'));  // 5

        // match 返回匹配字符串的数组,如果没有匹配则返回null
        // search 返回匹配字符串的首字符位置索引
        let str1="welcome to the world of JS!";
        let str2=str1.match("world");
        let str3=str1.search("world");
        console.log(str2);  // Array [ "world" ]
        console.log(str2[0]);  // 结果为"world"
        console.log(str3);     // 结果为15

        // x.substr(start, length) ----start表示开始位置,length表示截取长度
        let str4='abcdefgh';
        let str5=str4.substr(2,4);
        console.log(str5);  // cdef
        // x.substring(start, end) ----end是结束位置
        console.log('++++',str4.substring(2,4));  // cd

        // x.slice(start, end)     ----切片操作字符串
        console.log('---------');
        console.log(str4.slice(1,3));
        console.log(str4.slice(1,));
        console.log(str4.slice(1,-1));

        // 字符串替换
        let str6 = 'alnk';
        console.log(str6.replace('a','A'));

        // 分割字符串
        let str7 = 'hello world';
        console.log(str7.split(' ')); // Array [ "hello", "world" ]
    </script>
</head>
<body>
</body>
</html>




数组对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 数组
        let arr = [123, 345, 567, 'hello'];
        console.log(arr);
        console.log(arr[1]);

        // join方法
        console.log(arr.join('---'));  // 123---345---567---hello

        // concat 和python的extend有点像
        let a = [1, 2, 3];
        let b = a.concat(4, 5);
        console.log(b);  // Array(5) [ 1, 2, 3, 4, 5 ]

        // 数组排序 reverse sort
        let a1 = [32, 12, 111, 333];
        // reverse 翻转
        // a1.reverse();
        // console.log(a1);  // Array(4) [ 333, 111, 12, 32 ]

        // sort 排序:不是按照数字大小排序的,按照首字母排序的,先比较第一个字母,然后在比较第二个
        // a1.sort();
        // console.log(a1);  // Array(4) [ 111, 12, 32, 333 ]
        // 扩展,按照数字大小排序
        // function intSort(a,b) {
        //     if (a>b) {
        //         return 100;  // 为正数就可以
        //     } else if (a<b) {
        //         return -1;
        //     } else {
        //         return 0;
        //     }
        // }
        function intSort(a, b) {
            return a - b;
        }

        console.log('====');
        console.log(a1.sort(intSort));  // Array(4) [ 12, 32, 111, 333 ]

        // 数组切片操作
        console.log('+++');
        let arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
        let arr2 = arr1.slice(2, 4); // c,d
        let arr3 = arr1.slice(4);  //
        let arr4 = arr1.slice(2, -1);
        console.log(arr2);
        console.log(arr2.toString());  //结果为"c,d" 转化为字符串类型了
        console.log(arr3.toString());  //结果为"e,f,g,h"
        console.log(arr4.toString());  //结果为"c,d,e,f,g"

        // 删除子数组
        let a4 = [1, 2, 3, 4, 5, 6, 7, 8];
        a4.splice(1, 2);  // 从索引1开始,删除2个元素
        console.log(a4);  // Array(6) [ 1, 4, 5, 6, 7, 8 ]
        a4.splice(1, 1);  // 从索引1开始,删除1个元素
        console.log(a4); // Array(5) [ 1, 5, 6, 7, 8 ]
        a4.splice(1, 0, 2, 3);  // 在索引为1的位置 插入2个元素2和3,0表示插入新元素
        console.log('--');
        console.log(a4);  // Array(7) [ 1, 2, 3, 5, 6, 7, 8 ]
        a4.splice(-1, 0, 'a', 'b');
        console.log('-1', a4);

        // 数组的push和pop
        // push是将value值添加到数组的结尾
        let arr9 = [1, 2, 3];
        arr9.push(4, 5);
        console.log(arr9);  // Array(5) [ 1, 2, 3, 4, 5 ]
        arr9.push([6, 7,]);
        console.log(arr9); // Array(6) [ 1, 2, 3, 4, 5, (2) […] ]
        // pop是将数组x的最后一个元素删除
        arr9.pop();  // 注意删除了最后添加的[6,7]这个数组
        console.log(arr9);  // Array(5) [ 1, 2, 3, 4, 5 ]
        arr9.pop();
        console.log(arr9);  // Array(4) [ 1, 2, 3, 4 ]

        // shift 和 unshift  对索引为0的地方进行操作
        // unshift 添加
        let ar = [1, 2, 3];
        ar.unshift(4, 5);
        console.log(ar);  // Array(5) [ 4, 5, 1, 2, 3 ]
        ar.unshift([8, 9]);
        console.log(ar); // Array(6) [ (2) […], 4, 5, 1, 2, 3 ]
        // shift 删除
        ar.shift();
        console.log(ar);  // Array(5) [ 4, 5, 1, 2, 3 ]
        ar.shift();
        console.log(ar);  // Array(4) [ 5, 1, 2, 3 ]
    </script>
</head>
<body>
</body>
</html>




date对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // date对象
        date = new Date();
        console.log('==');
        console.log(date);  // Wed Apr 17 2019 10:43:38 GMT+0800 (中国标准时间)
        console.log(date.toLocaleString());  // 2019/4/17 上午10:44:37
        console.log(date.toLocaleDateString()); // 2019/4/17
        console.log(date.toLocaleTimeString()); // 上午10:45:00
        console.log(date.getFullYear());  // 2019 年
        console.log(date.getMonth());   // 3 月 获得当前月份 js中月份是从0到11
        console.log(date.getDate());  // 17 日
        console.log(date.getDay());  // 3 表示周三
        console.log(date.getHours());  // 10 时
        console.log(date.getMinutes());  // 47 分
        console.log(date.getSeconds());  // 26 秒
    </script>
</head>
<body>
</body>
</html>




math对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // math对象 和数学相关的
        console.log(Math.abs(-33));  // 绝对值
        console.log(Math.floor(1.22));  // 1
        console.log(Math.floor(1.999)); // 1
        console.log(Math.ceil(2.999)); // 3
        console.log(Math.ceil(2.2)); // 3
        console.log(Math.pow(2,3)); // 8 平方
        console.log(Math.random());  // 随机值
        console.log(Math.random());
        console.log(Math.random());
    </script>
</head>
<body>
</body>
</html>




函数对象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 函数对象
        /*
        function 函数名(参数1,....) {
            函数体
        }
        */
        function foo() {
            console.log('foo')
        }
        foo(); // 函数调用


        //  参数不对齐,也不报错
        function f1(x, y, z) {
            console.log(x + y);
            console.log(z); // undefined
            console.log(arguments) // 所有传入的参数都会放到这个关键字里 Arguments { 0: 1, 1: 2, … }
        }
        f1(1, 2); // 参数不对齐,也不会报错


        // arguments 应用 累加
        function add() {
            let ret = 0;
            for (let i = 0; i < arguments.length; i++) {
                ret += arguments[i];
            }
            return ret;
        }
        ret = add(1,2,3,4);
        console.log(ret);  // 10

        // 匿名函数
        (function(x,y) {
           console.log(x+y);
        })(4,5);  // 9
    </script>
</head>
<body>
</body>
</html>




bom操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // bom 控制浏览器对象
        // window对象弹框
        // window.alert(123);
        // window.alert('还有10分钟关机');
        //
        // let flag = window.confirm('你是否还继续游戏');
        // console.log(flag);
        //
        // let str1 = window.prompt('请输入');
        // console.log(str1);

        // 弹窗跳转
        // window.open('http://www.baidu.com','http://www.baidu.com','width=600,height=400,top=200,left=200');
        // window.close()  // 关闭窗口


        // 定时方法
        // function foo() {
        //     console.log('123');
        // }
        // let ID = setInterval(foo,1000);  // 每隔1s执行一下foo函数,如果不停止,会一直执行
        // //
        // // 取消定时
        // clearInterval(ID);
        //
        //
        // // 隔多久执行一次,只执行一次
        // setTimeout(function () {
        //     console.log('alnk')
        // },2000)
    </script>
</head>
<body>
</body>
</html>




定时器案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        // 获取时间,填充数据函数
        function foo() {
            // 获取当前时间
            let date = new Date();
            let now_date = date.toLocaleString();
            console.log(now_date);

            // 把数据填充到input标签
            let ele = document.getElementById('timer');
            ele.value = now_date;
        }


        // 定时函数
        let ID; // 全局变量
        function start() {
            if (ID===undefined) {
                foo();  // 防止点击按钮要1s以后才会填充数据
                ID = setInterval(foo,1000);
            }
        }


        // 停止函数
        function end() {
            clearInterval(ID);
            ID = undefined;  // 重置ID状态
        }
    </script>
</head>
<body>

<input type="text" name="" id="timer">

<button onclick="start()">start</button>

<button onclick="end()">end</button>

</body>
</html>




dom对象简介

DOM对象 --- document object model 文档对象控制
    DOM对象 == DOM节点
        1、document 文档对象
        2、element  标签对象

    一 查找标签
        1、直接查找
            document.getElementById(“idname”)         按照ID查找              dom对象
            document.getElementsByTagName(“tagname”)  按照标签查找             dom对象集合:[dom对象,dom对象2,...]
            document.getElementsByName(“name”)        按照标签的name属性来      dom对象集合:[dom对象,dom对象2,...]
            document.getElementsByClassName(“name”)   按照class值来查找         dom对象集合:[dom对象,dom对象2,...]

        2、导航查找
            parentElement           // 父节点标签元素     # dom对象
            children                // 所有子标签         # dom对象集合
            firstElementChild       // 第一个子标签元素    # dom对象
            lastElementChild        // 最后一个子标签元素  # dom对象
            nextElementSibling      // 下一个兄弟标签元素  # dom对象
            previousElementSibling  // 上一个兄弟标签元素  # dom对象

    二 操作标签
        (1) 操作标签的文本
        (2) 操作标签的value
        (3) 操作标签的属性
        (4) 操作标签的class属性(******)
        (5) 操作标签的节点增删改查 (******)




操作标签文本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--注意这里的this关键词的意思是:点击哪个标签,就触发哪个标签的foo()-->
    <div class="c1" onclick="foo(this)">alnk</div>
    <div class="c1" onclick="foo(this)">tom</div>
    <div class="c1" onclick="foo(this)"><a href="#">jerry</a></div>

    <script>
        function foo(self) {
            console.log(self);
            // 获取dom对象的文本值
            console.log(self.innerText);
            console.log(self.innerHTML);
            // 给dom对象的文本值重新赋值
            self.innerHTML = "<a href='#'>yuan</a>";     // 会按照标签显示
            // self.innerText="<a href='#'>yuan</a>";    // 按照纯文本显示
        }
    </script>
</body>
</html>




事件绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" name="" id="i1">
    <div class="c1">alnk</div>
    <div class="c1">tom</div>
    <div class="c1"><a href="#">jerry</a></div>

    <!-- script写在这里的好处,可以加快网页打开的速度,先显示基本的文本 -->
    <script>
        /*
        事件绑定样式
        dom对象.onclick=function () {}
         */

        // 举例1 绑定标签1
        // 1 查找标签
        i1 = document.getElementById('i1');
        // 2 绑定标签
        i1.onclick = function () {
            alert(123);
        };

        // 举例2 绑定标签2
        // 1 找到标签,是一个数组
        let eles = document.getElementsByClassName('c1');
        // 2 循环绑定标签
        for (var i=0;i<eles.length;i++) {
            eles[i].onclick = function () {
                // this:dom对象,即事件触发的标签
                console.log(this);
                this.innerHTML='yuan';
                // 坑点,这里的this不能用eles代替
                // console.log(i);  // 3
                // eles[i].innerHTML="yuan";  // 代码循环结束以后,i=3
            }
        }
    </script>
</body>
</html>




操作value值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="i1" value="alnk">
    <textarea name="" id="i2" cols="30" rows="10"></textarea>
    <select name="" id="i3">
        <option value="hebei">河北省</option>
        <option value="hunan" >湖南省</option>
        <option value="henan" selected="selected">河南省</option>
    </select>
    <button id="change">change</button>

    <script>
        let ele1 = document.getElementById('i1');
        let ele2 = document.getElementById('i2');
        let ele3 = document.getElementById('i3');
        let change = document.getElementById('change');

        change.onclick = function () {
            ele1.value="tom";
            ele2.value='jerry';
            ele3.value='hunan';

            console.log(ele1.value);
            console.log(ele2.value);
            console.log(ele3.value);
        }
    </script>
</body>
</html>




属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="i1" oldboy="35" alnk="123"></div>
    <button id="change">change</button>

    <script>
        let ele = document.getElementById('i1');
        let change = document.getElementById('change');

        // 属性,自定义属性
        change.onclick = function () {
            ele.setAttribute("oldboy",55);  // 修改
            ele.setAttribute('xxx',999);  // 增加
            ele.removeAttribute('alnk');  // 删除
        }
    </script>
</body>
</html>




class属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            color: red;
        }

        .c2 {
            background-color: #5f5750;
        }

        .c3 {
            font-size: 40px;
        }

        .c4 {
            border: 1px red solid;
        }
    </style>
</head>
<body>
    <div class="c1 c4">alex</div>
    <button id="change">change</button>

    <script>
        let change = document.getElementById('change');
        let ele = document.getElementsByClassName('c1')[0];

        change.onclick = function () {
            // ele.classList.add('c2');
            ele.classList.add('c2','c3');  // 增加class属性值
            ele.classList.remove('c4');    // 删除class属性值
        }
    </script>
</body>
</html>




菜单栏案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .caidan-pg,.content-pg {
            height: 600px;
            float: left;
            padding: 15px;

        }

        .caidan-pg {
            background-color: #7A77C8;

            width: 25%;
        }

        .content-pg {
            width: 70%;
            background-color: #5f5750;
        }

        .title {
            text-align: center;
            font-size: 30px;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>

<div class="outer-pg">
    <!--菜单栏-->
    <div class="caidan-pg">
        <div class="items">
            <div class="title">菜单1</div>
            <div class="conn">
                <p>111</p>
                <p>111</p>
                <p>111</p>
            </div>
        </div>
        <div class="items">
            <div class="title">菜单2</div>
            <div class="conn hide">
                <p>111</p>
                <p>111</p>
                <p>111</p>
            </div>
        </div>
        <div class="items">
            <div class="title">菜单3</div>
            <div class="conn hide">
                <p>111</p>
                <p>111</p>
                <p>111</p>
            </div>
        </div>
    </div>

    <!--内容区-->
    <div class="content-pg"></div>
</div>

<script>
    let eles = document.getElementsByClassName('title');
    let conn_eles = document.getElementsByClassName('conn');

    for (let i=0;i<eles.length;i++) {
        eles[i].onclick = function () {
            // 隐藏所有菜单里面的内容
            for (var j=0;j<conn_eles.length;j++) {
                conn_eles[j].classList.add('hide');
            }

            // 删除隐藏
            this.nextElementSibling.classList.remove('hide');
        }
    }
</script>
</body>
</html>



posted @ 2021-05-26 16:20  李成果  阅读(80)  评论(0编辑  收藏  举报