当前位置:网站首页>JS case exercise (classic case of teacher pink)

JS case exercise (classic case of teacher pink)

2022-08-11 06:35:00 Sherry Shen

Recorded while watchingPink老师jsCases encountered in the tutorial that are worth writing over and over again!

1. 翻转任意数组

function Change() {
    
            var newArr = [];
            for (var i = arguments.length - 1; i >= 0; i--) {
    
                newArr[newArr.length] = arguments[i]
            }
            return newArr;
        }

        console.log(Change(1, 2345, 6, 8, 89, 5, 9));Insert generation
var arr = [1, 2345, 6, 8, 89, 5, 9];
        console.log(arr.reverse());

2.求red出现的位置和次数

var arr = ['red', 'blue', 'red', 'green', 'pink', 'red', 'red'];
        var index = arr.indexOf('red');

        var number = 0;
        while (index != -1) {
    
            console.log(index);
            var index = arr.indexOf('red', index + 1);
            number++;

        }
        console.log(number);

3.替换字符

var str5 = 'abaasdffgggghhhhjkkkgfdddssssss23444343434';
        while (str5.indexOf("s") !== -1) {
    
        str5 = str5.replace('s', 'u');
        }
        console.log(str5);

var str5 = 'abaasdffgggghhhhjkkkgfdddssssss23444343434';
        do {
    
            var index = str5.indexOf('s');
            console.log(index);
            str5 = str5.replace('s', 'u');
        } while (index !== -1)

        console.log(str5);

注意

  1. 字符串.replace(被替换的字符串, 要替换为的字符串);
  2. because it was replaced,Use AutoFind Next,We don't need to giveindex加一了
  3. 但是indexofNeed to change each cycle

4.Find the character with the most occurrences and the number of occurrences in the above string

 var str = "abcoefoxyozzopp";
        var o = {
    };
        for (var i = 0; i < str.length; i++) {
    
            var chars = str.charAt(i); // chars 是 字符串的每一个字符
            if (o[chars]) {
    
                // o[chars] 得到的是属性值
                o[chars]++;
            } else {
    
                o[chars] = 1;
            }
        }
        console.log(o);
var max = 0;
        var ch = "";
        for (var k in o) {
    
            // k 得到是 属性名
            // o[k] 得到的是属性值
            if (o[k] > max) {
    
                max = o[k];
                ch = k;
            }
        }
        console.log(max);
        console.log("最多的字符是" + ch);

5.Deselect all forms

<!-- 表单全选取消全选 -->
    <table>
        <thead>
            <td><input type="checkbox" id="j_cbAll"></td>
            <td>商品</td>
            <td>价钱</td>
        </thead>
        <tbody id="j_tb">
            <tr>
                <td><input type="checkbox"></td>
                <td>iPhone6</td>
                <td>1000</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>2</td>
                <td>100</td>
            </tr>
        </tbody>
    </table>
 <script>
 //1.Click on the top one,Full selection below
        var j_cbAll = document.getElementById('j_cbAll');
        var tds = document.getElementById('j_tb').querySelectorAll('input');
        j_cbAll.onclick = function () {
    
            for (var i = 0; i < tds.length; i++) {
    
                tds[i].checked = this.checked;
            }
        }
        //2. 下面复选框需要全部选中,The first one above will be selected
        for (var i = 0; i < tds.length; i++) {
    
            tds[i].onclick = function () {
    
                var flag = true;
                //每次点击都要检查下面的4个按钮是否全被选中
                for (var j = 0; j < tds.length; j++) {
    
                    if (!tds[j].checked) {
    
                        flag = false;
                        break; //退出for循环,这样可以提高执行效率,只要有一个没选中,就可以为false了
                    }
                }
                j_cbAll.checked = flag;
            }
        }
    </script>

注意:

  1. Note whether an array or an element is returned
  2. Watch out for function events,The nested hierarchy of judgments and loops
  3. 是this.checked不是直接checked
  4. 引入新变量flag是用于:Use the result of a certain judgment in the loop to affect the result of the end of all loops.

6.tab栏切换

<!-- tab栏切换布局分析 -->
    <div class="tab">
        <div class="nav">
            <ul>
                <li class="current">商品介绍</li>
                <li>规格与保证</li>
                <li>售后保障</li>
                <li>商品评价</li>
                <li>手机社区</li>
            </ul>
        </div>
        <div class="content">
            <div class="item visit">商品介绍模块内容</div>
            <div class="item ">规格与保证内容</div>
            <div class="item">售后保障内容</div>
            <div class="item ">商品评价内容</div>
            <div class="item ">手机社区内容</div>
        </div>
    </div>

功能1:点击每个LiIts color will change(排他思想)
功能2:The options below correspond one by one to the above

 <script>
        lis = document.querySelector('.nav').querySelectorAll('li');
        divs = document.querySelector('.content').querySelectorAll('div');
        items = document.querySelectorAll('.item');
        for (var i = 0; i < lis.length; i++) {
    
            // 开始给5个小li,设置索引号
            lis[i].setAttribute('index', i);
            lis[i].onclick = function () {
    
//1.上面的选项卡模块,Clicking on one of the current background color is red,其余不变(排他思想),修改类名的方式
              //干掉所有人 其余的 li清除class这个类
                for (var i = 0; i < lis.length; i++) {
    
                    lis[i].className = ''
                }
                //留下我自己
                this.className = 'current'
//2. 内容显示模块:The lower tabs correspond one-to-one with the upper tabs,相匹配
                var index = this.getAttribute('index');
                // 隐藏所有其他的内容
                for (var i = 0; i < items.length; i++) {
    
                    items[i].style.display = 'none'
                }
                items[index].style.display = 'block'
            }
        }
    </script>

注意:
1.You need to pay attention to whether you get a class or a label
2.How to correspond to the above and below content one by one:The main thing is to use the settings for eachli设置新属性,Let the new property be the same as the index number,This way clicks smallli时,The box below gets through the smallliThe new property of li索引号.
3.或者说,The first step of exclusive thinking is to make all elements the same by looping,So the second step is how to add special formatting to yourself or the linked box?
(1)If you add a special format to yourself:可以通过this指向函数的调用者,也就是自己.
(2)If it is to add a special format to the one-to-one correspondence box:By adding new properties,Encapsulate your own index number in a new property,Let the linked box call the new property to get the index number to get the special format.

7.新浪下拉菜单案例

<ul class="nav">
        <li>
            <a href="">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
        <li>
            <a href="">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
        <li>
            <a href="">微博</a>
            <ul>
                <li><a href="">私信</a></li>
                <li><a href="">评论</a></li>
                <li><a href="">@我</a></li>
            </ul>
        </li>
    </ul>
// <!-- 获取元素 -->
        //1.所有的标签
        var nav = document.querySelector('.nav');
        var lis = nav.children;//得到4个小li
        for (var i = 0; i < lis.length; i++) {
    
            lis[i].onmouseover = function () {
    
                this.children[1].style.display = 'block';
                //第二个孩子
            }
            lis[i].onmouseout = function () {
    
                this.children[1].style.display = 'none';
            }
        }

注意

  1. 导航栏里面的li都要有鼠标经过效果,所以需要循环注册鼠标事件
  2. 核心原理:当鼠标经过li里面的第二个孩子ul显示,当鼠标离开,则ul隐藏
  3. Code details:注意是.style.display
  4. Generally there is a cyclic relationshipi时,用this指向,Otherwise can't find which one it isi

8.留言案例

<textarea name="" id="" cols="30" rows="10">123</textarea>
    <button>发布</button>
    <ul>
        
    </ul>

添加留言

var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        btn.onclick = function () {
    
            if (text.value == '') {
    
                alert('您没有输入内容');
                return false;
            } else {
    
                var li = document.createElement('li');
                li.innerHTML = text.value;
                ul.appendChild(li);
//ul.insertBefore(li,ul.children[0]);
            }
        }

注意

  1. Determine if there is any input content‘==’不是‘=’
  2. 先创建元素,再添加元素
  3. 注意是text.value

删除留言

    <textarea name="" id=""></textarea>
    <button>发布</button>
    <ul>
 
    </ul>
    <script>
        // 1. 获取元素
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. 注册事件
        btn.onclick = function() {
    
            if (text.value == '') {
    
                alert('您没有输入内容');
                return false;
            } else {
    
                // console.log(text.value);
                // (1) 创建元素
                var li = document.createElement('li');
                // 先有li 才能赋值
                li.innerHTML = text.value + "<a href='javascript:;'>删除</a>";
                // (2) 添加元素
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
                // (3) 删除元素 删除的是当前链接的li 它的父亲
                var as = document.querySelectorAll('a');
                for (var i = 0; i < as.length; i++) {
    
                    as[i].onclick = function() {
    
                        // node.removeChild(child); 删除的是 li 当前a所在的li this.parentNode;
                        ul.removeChild(this.parentNode);
                    }
                }
            }
        }
    </script>

注意:

  1. .阻止链接跳转需要添加javascript:void(0);或者javascript:;
  2. li.innerHTML = text.value + "删除"注意位置,Also pay attention to single or double quotes
  3. node.removeChild(child); 删除的是 li 当前a所在的li this.parentNode;注意this的引入

9.动态生成表格

         <!-- 动态生成表格 -->
    <table cellspacing="0">
        <thead>
            <tr><th>姓名</th><th>科目</th><th>成绩</th><th>操作</th></tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <script>
        //1.学生的数据
        var data = [
            {
    
                name: '熊阳阳',
                subject: 'js',
                score: 80
            },
            {
    
                name: 'conan',
                subject: '数学',
                scroe: '100'
            },
            {
    
                name: 'conan',
                subject: '柯学',
                scroe: '100'
            }
        ]
        //2.根据数组长度,创建行
        var tbody = document.querySelector('tbody');
        for (var i = 0; i < data.length; i++) {
    
            // 2.1创建行
            var tr = document.createElement('tr');
            tbody.appendChild(tr)
            // 2.2创建单元格
            for (var k in data[i]) {
    
                console.log(data[i].k)
                var td = document.createElement('td');
                tr.appendChild(td);
           // 2.3The cell is filled with content
                td.innerHTML = data[i][k];
            }
            // 2.4创建删除单元格 
            var td = document.createElement('td');
            tr.appendChild(td);
            td.innerHTML = '<a>删掉</a>'
        }
 
        //3.点击删掉,删掉
        var tbody = document.querySelector('tbody');
        var as = document.querySelectorAll('a');
        for (var i = 0; i < as.length; i++) {
    
            as[i].onclick = function () {
    
                //取出被点击a的父节点(a的父节点是td,td的父节点才是tr)
                var del_td = this.parentNode;
                //是tbody删掉tr——注意是tbody啦
                tbody.removeChild(del_td.parentNode)
            }
        }
    </script>

注意
Figure out the parent-child node relationship

10.模拟京东快递单号查询

完整代码
注意
1.Notice the new properties of the formplaceholder,Also pay attention to him andvalue的区别
2.Note the trianglecss写法:用before

11.Jingdong countdown effect

完整代码
注意
1.It is better to introduce variables outside the function for easy maintenance
2.最好采用封装函数的方式,这样可以先调用一次这个函数,Prevents blank issues when the page is first refreshed

12.发送短信案例

<!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>
    手机号码: <input type="number"> <button>发送</button>
    <script>
        // 按钮点击之后,会禁用 disabled 为true 
        // 同时按钮里面的内容会变化, 注意 button 里面的内容通过 innerHTML修改
        // 里面秒数是有变化的,因此需要用到定时器
        // 定义一个变量,在定时器里面,不断递减
        // 如果变量为0 说明到了时间,我们需要停止定时器,并且复原按钮初始状态
        var btn = document.querySelector('button');
        var time = 3; // 定义剩下的秒数
        btn.addEventListener('click', function() {
    
            btn.disabled = true;
            var timer = setInterval(function() {
    
                if (time == 0) {
    
                    // 清除定时器和复原按钮
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.innerHTML = '发送';
                    //time=3;
                } else {
    
                    btn.innerHTML = '还剩下' + time + '秒';
                    time--;
                }
            }, 1000);

        })
    </script>
</body>

</html>

注意
1.disabled=true或者false不要加引号
2.The timer will only start when clicked,So the timer function should be inside the click function
3.当时间为0后,Pay attention to restore settings and remember to clear the timer
If you want multiple clicks,可以再加上time=3;

13.相似案例:5s后跳转页面

<body>
    <button>点击</button>
    <div></div>
    <script>
        var btn = document.querySelector('button');
        var div = document.querySelector('div');
        var timer = 5;
        setInterval(function() {
    
            if (timer == 0) {
    
                location.href = 'http://www.itcast.cn';
            } else {
    
                div.innerHTML = '您将在' + timer + '秒钟之后跳转到首页';
                timer--;
            }

        }, 1000);
    </script>
</body>


14.用户登录


<body>
    <form action="index.html">
        用户名: <input type="text" name="uname">
        <input type="submit" value="登录">
    </form>
</body>


<body>
    <div></div>
    <script>
        console.log(location.search); // ?uname=andy
        // 1.先去掉? substr('起始的位置',截取几个字符);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. 利用=把字符串分割为数组 split('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var div = document.querySelector('div');
        // 3.把数据写入div中
        div.innerHTML = arr[1] + '欢迎您';
        // 这样我们就能获取到路径上的URL参数
    </script>
</body>


原网站

版权声明
本文为[Sherry Shen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110515295605.html