Blogger Information
Blog 26
fans 1
comment 0
visits 18858
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
7月11号作业
坏人也温柔de陈词滥调
Original
754 people have browsed it

事件代理又称之为事件委托是JavaScript中常用绑定事件的常用技巧顾名思义事件代理即是把原本需要绑定在子元素的响应事委托给父元素让父元素担当事件监听的职务事件代理的原理是DOM元素的事件冒泡

留言板

实例

<!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>留言板</title>
</head>
<body>

<label for="comment">请留言:</label>
<input type="text" id="comment" onkeydown="addComment1(this)" autofocus>

<!-- 留言列表-->
<ul id="list"></ul>

<script>
    function addComment1(comment) {
        if (event.keyCode === 13) {

            // 1. 创建新留言,并添加到留言列表中
            var item = document.createElement('li');

            // 添加删除功能,只需要给给当前留言后面添加一个删除按钮, 再创建对象的事件方法即可
            // item.append(content); // 内容中不支持html标签
            item.innerHTML = comment.value;
            item.innerHTML += '  <button onclick="del1(this)">删除</button>';

            // 2. 将留言添加到列表中
            var list = document.querySelector('#list');

            // 如果当前留言列表为空, 则直接插入到到尾部,否则就插入到第一条留言之前
            if (list.childElementCount === 0) {
                // 还可以用以下方法判断ul.children.length / ul.childNodes.length
                list.append(item);
            } else {
                // 如果列表已有留言,则插入到新一条之前
                var first = list.firstElementChild;
                // list.insertBefore(item,first);
                list.prepend(item,first);
            }

            // 3. 清空文本框
            comment.value = '';
        }
    }

    // 删除留言函数
    function del(ele) {
        // ele 代表的当前的删除按钮, 我要删除的不是它,而是它的父节点,就是当前li

        // confirm(): 的弹窗与alert()不同, 除了有确定按钮外, 还有一个取消,点确定返回true,取消返回false
        if (confirm('是否删除?')) {
            // 获取按钮的父元素 li
            var li = ele.parentNode;
            // 删除节点只能在当前节点的父元素上进行
            // li.parentNode: 返回li的父节点, 就是 ul
            // removeChild(): 从当前父节点上移除子节点
            li.parentNode.removeChild(li);
        }
        // 其实默认返回false,下面这条语句可以省略
        return false;
    }

    // 进一步简化的留言函数
    function del1(ele) {
        return confirm('是否删除?') ? ele.parentElement.remove() : false;
    }

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

~H}9Z)H~QWIC@K7OZVSUDYG.png


运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:事件委托 , 在开发中用得很多, 但要注意是有前提的
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!