
jquery 给动态生成的标签绑定事件的几种方
1个回答
展开全部
1、动态绑定事件:
<div id=box></div>
<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>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询