冒泡事件和事件代理操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1. 事件冒泡,事件代理</title>
</head>
<body>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
<script>
// 事件冒泡
// console.log('事件冒泡');
const limao = document.querySelectorAll('li');
limao.forEach( function( item){
item.onclick = function (){
console.log(event.currentTarget.textContent);
}
});
document.querySelector('ul').onclick = () => console.log('li的父级ul:', event.currentTarget);
</script>
<ul class="list">
<li data-name="item1">item1</li>
<li data-name="item2">item2</li>
<li data-name="item3">item3</li>
<li data-name="item4">item4</li>
<li data-name="item5">item5</li>
</ul>
<script>
console.log('事件代理');
const ul = document.querySelector('.list');
ul.onclick = function () {
console.log(event.target, event.target.dataset.name);
console.log(event.currentTarget);
}
</script>
</body>
</html>
冒泡事件
事件代理
字符串API,进行演示(MDN)
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>字符串API,进行演示(MDN)</title>
</head>
<body>
<ul class="xz">
<li>one two three four five</li>
<li>WHO IS MY NAME?</li>
<li>WHO IS MY NAME?</li>
<li>WHO IS MY NAME?</li>
<li> WHO IS MY NAME? </li>
</ul>
<script>
console.log('字符串API');
const xz= document.querySelector(".xz");
let li_one = document.querySelector(".xz li:first-of-type").textContent.toUpperCase();
li_one = '<li>'+'小写转换大写-' +li_one +'</li>';
xz.insertAdjacentHTML('afterbegin',li_one);
let li_two = document.querySelector(".xz li:nth-of-type(2)").textContent.toLowerCase();
li_two = '<li>'+ '大写转换小写-' +li_two+'</li>';
xz.insertAdjacentHTML('afterbegin',li_two);
let li_three = document.querySelector(".xz li:nth-of-type(3)").textContent.bold();
li_three = '<li>'+ '文字加粗-' +li_three+'</li>';
xz.insertAdjacentHTML('afterbegin',li_three);
let li_four = document.querySelector(".xz li:nth-of-type(4)").textContent.big();
li_four = '<li>'+ '文本加大-' +li_four+'</li>';
xz.insertAdjacentHTML('afterbegin',li_four);
let li_five = document.querySelector(".xz li:last-of-type").textContent.trim();
li_five = '<li>'+ '两端删除空白字符-' +li_five+'</li>';
xz.insertAdjacentHTML('afterbegin',li_five);
</script>
</body>
</html>
效果如下