代理模式比较简单,主要的核心代码记录一下
ul {
margin-bottom: 10px;
overflow: hidden;
width: 200px;
}
li {
list-style: none;
float: left;
width: 20px;
height: 20px;
background: red;
color: #fff;
margin: 10px;
text-align: center;
}
<ul id="lists">
</ul>
<ul id="lists2">
</ul>
<div id="article">
<p>第一段文字</p>
</div>
<button>我是一个按钮</button>
<script>
var str = ''
for (var i = 0; i < 40; i++) {
var oLi = '<li>' + i + '</li>'
str += oLi
}
document.getElementById('lists').innerHTML = str
</script>
<script>
var fragment = document.createDocumentFragment()
for (var i = 1; i < 21; i++) {
var oLi = document.createElement('li')
oLi.innerHTML = i
fragment.appendChild(oLi)
}
document.getElementById('lists2').appendChild(fragment)
</script>
<script>
//添加事件 bad
/* var oUl = document.getElementById('lists2'),
li = oUl.getElementsByTagName('li'), len = li.length - 1
for (var i = 0; i < len; i++) {
li[i].onclick = function () {
this.style.backgroundColor = 'gray'
}
} */
</script>
<script>
//最佳事件,利用子元素的事件冒泡,触发定义在父元素上的事件
var oUl = document.getElementById('lists2')
oUl.onclick = function (e) {
var e = e || window.event, target = e.target || e.srcElement
if (target.nodeName.toLowerCase() === 'li') {
target.style.backgroundColor = 'gray'
}
}
</script>
<script>
//为动态添加的子元素添加事件
var article = document.getElementById('article')
article.onclick = function (e) {
var e = e || window.event, target = e.target || e.srcElement
if (target.nodeName.toLowerCase() === 'p') {
target.innerHTML = '我要更改这段内容'
}
}
var newP = document.createElement('p')
newP.innerHTML = "新增的一段文字"
article.appendChild(newP)
</script>
<script>
//可以避免内存泄露,减少引用事件
//数据分发
/* $.get('./deal?name=message', (res) => { })
$.get('./deal?name=aside', (res) => { })
$.get('./deal?name=main', (res) => { })
$.get('./deal?name=banner', (res) => { }) */
//请求太多,造成资源浪费
var post = {
banner(res) { },
aside(res) { },
main(res) { },
message(res) { },
}
/* $.get('./deal.php', (res) => {
for (var i in res) {
Deal[i] && Deal[i](res[i])
}
}) */
//委托模式封装一个简易事件
var delegate = function (context, target, handle, cb) {
context.addEventListener(handle, function (e) {
console.log(e, 'ppp')
var e = e || window.event, target1 = e.target || e.srcElement
if (target1.nodeName.toLowerCase() === target) {
console.log(cb, 'ecb')
cb && cb()
}
}, false)
}
delegate(document.body, 'button', 'click', function () {
alert("委托成功")
})
</script>