Open erbing opened 5 years ago
<body>
<ul>
<li class='target'>
<span>test</span>
</li>
</ul>
<script>
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
document.getElementsByTagName('ul')[0].addEventListener('click', (e)=>{
let target = getEventTarget(e);
if(target.classList.contains("target")){
alert("test");
}
})
</script>
</body>
let appRom = document.getElementById('delegation')
let ulDom = appRom.children[0]
// 绑定方法
const handle = (dom, type, callback) => {
dom.addEventListener(type,callback)
}
// 获取 target 对象方法 兼容
const getEventTarget = (e) => {
e = e || window.event
return e.target || e.srcElement
}
// 动态添加一个 btn 按钮
const createBtn = () => {
let createBtnDom = document.createElement('button')
createBtnDom.textContent = '添加'
createBtnDom.className = 'add-btn'
handle(createBtnDom, 'click', ()=>{
let createLiDom = document.createElement('li')
createLiDom.textContent = 'hello, li~' + Math.random()
ulDom.appendChild(createLiDom)
})
return createBtnDom
}
// 执行 添加一个 btn 按钮 方法
let createBtnHtml = createBtn()
appRom.appendChild(createBtnHtml)
// 获得点击 target 的 innerHtml 方法
handle(appRom,'click',(e)=>{
let curTarget = getEventTarget(e)
if (curTarget.children && curTarget.children.length || curTarget.tagName == 'BUTTON') return false
return curTarget.innerHTML
})
<!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>
<div id="delegation">
<ul>
<li class='target'>
<span>test1</span>
</li>
</ul>
</div>
</body>
<script>
let appRom = document.getElementById('delegation')
let ulDom = appRom.children[0]
// 绑定方法
const handle = (dom, type, callback) => {
dom.addEventListener(type,callback)
}
// 获取 target 对象方法 兼容
const getEventTarget = (e) => {
e = e || window.event
return e.target || e.srcElement
}
// 动态添加一个 btn 按钮
const createBtn = () => {
let createBtnDom = document.createElement('button')
createBtnDom.textContent = '添加'
createBtnDom.className = 'add-btn'
handle(createBtnDom, 'click', ()=>{
let createLiDom = document.createElement('li')
createLiDom.textContent = 'hello, li~' + Math.random()
ulDom.appendChild(createLiDom)
})
return createBtnDom
}
// 执行 添加一个 btn 按钮 方法
let createBtnHtml = createBtn()
appRom.appendChild(createBtnHtml)
// 获得点击 target 的 innerHtml 方法
handle(appRom, 'click', (e)=>{
let curTarget = getEventTarget(e)
if (curTarget.children && curTarget.children.length || curTarget.tagName == 'BUTTON') return false
alert(curTarget.innerHTML)
})
</script>
</html>
class
为target
的li
可以 alert 出其所含内容(如上方代码点击弹出“test”)ul
动态新增li
元素的情况下,也要有相同效果js
实现,不使用jQuery\Vue\React\Angular
等框架