首先是樣式美化(僅僅是為了好看):
ul {
margin: 0;
padding: 0;
font-size: 0;
}
li {
display: inline-block;
font-size: 15px;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
cursor: pointer;
border-radius: 20%;
transition: border-radius 1s, background-color .5s, color .5s;
}
li:hover {
background-color: rgba(0,0,0,.3);
border-radius: 50%;
color: #fff;
}
html內(nèi)容(一個容器,加上id方便js選取):
<ul id="ul"></ul>
這里我們使用artTemplate做數(shù)據(jù)的渲染:
<script type="text/javascript" src="js/template-web.js" ></script>
<script type="text/template" id="tpl">
<% for(var i = 0; i < 9; i++){ %>
<% if (i<num) { %>
<li><%= i %></li>
<% } else { %>
<li><%= i %></li>
<% } %>
<% } %>
</script>
注意引入
template-web.js
將模板書寫到script
標(biāo)簽里面,注意:type="text/template"
// 定義一個方法
/*
* pr 代理事件的父級容器
* ch 綁定時間的子元素
* data 需要傳入的數(shù)據(jù)
* fn 回調(diào)
*/
function bind (pr, ch, data, fn) {
document.getElementById(pr).addEventListener('click', function (event) {
if (event.target.localName === ch) {
fn.call(event.target, da)
}
})
}
// 1.先綁定時間
bind('ul', 'li', {name:'張三'}, function (d) {
console.log(d, this.innerHTML)
})
// 定義要數(shù)據(jù)
var da = {
num: 5
}
// 用模板生成字符串
var html = template('tpl', da);
// 在容器`ul`中插入元素
document.getElementById('ul').innerHTML = html;
在上面的代碼中,我們先將事件綁定,在通過模板拼接字符串腿堤,在頁面中插入元素
如果不通過事件代理的方式直接通過綁定事件
document.getElementById(''ul).addEventListener("click", function () {
console.log(123);
})
// 或者
document.getElementById(''ul).onclick = function () {
console.log(123);
}
再之后插入的元素 是沒有click事件的。