批改状态:合格
老师批语:
元素事件的触发,默认会向上(父级)传递,当父级元素有同名事件时,会被自动触发,这种传递默认可以传至window。
...<body>...<ul><li>item1</li><li>item2</li><li>item3</li><li>item4</li><li>item5</li></ul><script>const items = document.querySelectorAll('li');console.log(items);items.forEach((item)=>(item.onclick = ()=>{console.log(event);//事件目标console.log(event.target);//事件主体console.log(event.currentTarget);}));document.querySelector('ul').onclick = (()=>console.log('li的父级ul:',event.currentTarget));document.body.onclick = (()=>console.log('ul的父级body:',event.currentTarget));document.documentElement.onclick = (()=>console.log('body的父级html:',event.currentTarget));document.onclick = (()=>console.log('html的父级document:',event.currentTarget));window.onclick = (()=>console.log('document的父级window:',event.currentTarget));</script>...</body>
点击item1,效果如下:
阻止事件冒泡
...<body>...<script>...//阻止冒泡event.stopPropagation();...</script>...</body>
点击li元素将不再有事件冒泡
将子元素事件委托在父元素的事件上触发,以简化代码。在事件代理/委托时,事件目标(target)和事件主体(currentTarget)是不一样的。
...<body>...<ul><!-- 自定义属性data-index是为了便于区分事件的触发者 --><li data-index="1">item1</li><li data-index="2">item2</li><li data-index="3">item3</li><li data-index="4">item4</li><li data-index="5">item5</li></ul><script>const ul = document.querySelector('ul');ul.onclick = ()=>{// target事件目标li,子元素,dataset.index引用li中data-index的值console.log('event.target:',event.target,event.target.dataset.index);// currentTarget事件主体ul,onclick是绑定在父元素ul上的console.log('event.currentTarget:',event.currentTarget);};</script>...</body>
选择点击li效果如下:
...<body>...<script>let str = 'php中文网';//转成大写console.log(str.toUpperCase());// 转成字符数组const arr = str.split('');console.log(str.split(''));console.log(arr[0],arr[4]);// 搜索console.log(str.startsWith('p')); //以“p”开头console.log(str.endsWith('网')); //以“网”结尾//处理console.log(str.slice(-3)); //保留倒数三个字符console.log(str.slice(-3).padStart(str.length,'*')); //从0-倒数第三个之间用*遮盖console.log(str.length);console.log(str.charAt(2));console.log(str.indexOf('中'));console.log(str.concat('(','https://php.cn',')'));console.log(str.replace('中文网','cn'));console.log(str.slice(0,3));console.log(str.substr(0,4));console.log(str.substr(-3,3));</script>...</body>

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