
<button id=btn>动态生成标签</button>
<script>
window.onload=function(){
document.getElementById("btn").onclick=function(){
var span=document.createElement("span")
span.innerHTML="点我"+Math.random()
span.onclick=function(){
alert(this.innerHTML)
}
document.getElementById("box").appendChild(span)
}
}
</script>
2、事件委托:
<div id=box></div><button id=btn>动态生成标签</button>
<script>
window.onload=function(){
document.getElementById("box").onclick=function(e){
var e=e||window.event
if(e.target!=e.currentTarget){
alert(e.target.innerHTML)
}
}
document.getElementById("btn").onclick=function(){
var span=document.createElement("span")
span.innerHTML="点我"+Math.random()
document.getElementById("box").appendChild(span)
}
}
</script>
可以通过事件代理方式加载事件,比如你的父容器是ul,ul下面的li是动态生成的,绑定点击事件可以这样写:
$('ul').on('click','li',function(){//code here})欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)