摘要:本篇jQuery教程探讨了事件代理jQuery.bind()方法,希望阅读本篇文章以后大家有所收获,帮助大家对jQuery的理解更加深入。
首先是样式美化(仅仅是为了好看):
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内容(一个容器,加上id方便js选取):
<ul id="ul"></ul>
这里我们使用artTemplate做数据的渲染:
<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标签里面,注意:type="text/template"
// 定义一个方法/*
* pr 代理事件的父级容器
* ch 绑定时间的子元素
* data 需要传入的数据
* fn 回调
*/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)
})
// 定义要数据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事件的。
本文由职坐标整理并发布,了解更多内容,请关注职坐标WEB前端jQuery频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号