批改状态:合格
老师批语:
- 实例演示事件代理的实现机制;
- 完成留言板,添加留言删除功能
- 自选不少于10个字符串方法进行练习
- 预习常用的数组方法
事件代理: 也叫”事件委托”,事件触发者通常是”事件绑定者”的子元素
body 中添加 html
<ul id="list"><li class="item">item1</li><li class="item">item2</li><li class="item">item3</li></ul>
// 父元素添加点击事件监听document.querySelector('ul#list').addEventListener('click', ev => {// 事件绑定者console.log(ev.currentTarget);// 事件触发者,通常是"事件绑定者"的子元素console.log(ev.target.innerHTML);});

body 中添加 html
<label><input type="text" id="msg" /></label><ol class="list"></ol>
// 留言板追加数据document.querySelector('#msg').addEventListener('keydown', ev => {// 非空回车时if (ev.key == 'Enter' && ev.currentTarget.value.trim().length > 0) {let msg = `<li>${ev.currentTarget.value} <a href="javascript:;" onclick="delMsg(this);">[删除]</a></li>`;// 新添加的留言在前document.querySelector('ol.list').insertAdjacentHTML('afterbegin', msg);// 清空上一条留言ev.currentTarget.value = '';}});// 删除留言时function delMsg(el) {document.querySelector('ol.list').removeChild(el.parentElement);}


let str = '';// 1. concat() 拼接str = str.concat('a', 'b', 'c', '|', 0, 1, 'd', 'e');// abc|01deconsole.log(str);// 2. slice(start, end) 取子串str = str.slice(1, 7);// bc|01dconsole.log(str);// 3. substr(start, length) 截取子串str = str.substr(1, 4);// c|01console.log(str);// 4. trim() 去掉首尾空格let str2 = ' empty ';str2 = str2.trim();// 返回 emptyconsole.log(str2);// 5. split() 字符串分割成数组let arr = str.split('|');// ["c", "01"]console.log(arr);// 6. indexOf() 子串首次出现位置let pos = str.indexOf('|');console.log(pos);// 7. replace() 字符串替换str = str.replace(/\|/i, '-');// c-01console.log(str);// 8. repeat() 重复次数字符串str = str.repeat(2);// c-01c-01console.log(str);// 9. lastIndexOf() 子串最后一次出现位置let lpos = str.lastIndexOf('-');// 返回 5console.log(lpos);// 10. search() 搜索子串// 返回 3console.log(str.search(/1c\-/));// ...

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号