給js動態創建的對象綁定事件
1、使用原生JS動態為動態創建的對象綁定事件
1-1、創建一個function,用來兼容IE8以下瀏覽器添加事件
function addEvent(el, type, fn) {
if(el.addEventListener){
el.addEventListener(type,fn,false)
}else if(el.attachEvent()){
el.attachEvent(‘on‘ + type,fn,false)
}else{
return false
}
}
1-2、使用JS創建對象,調用上面的方法
function append(){
var body=document.getElementsByTagName(‘body‘)[0];
var btn=document.createElement(‘button‘);
btn.type=‘button‘
btn.innerHTML=‘確定‘
addEvent(btn,‘click‘,function(){
console.log(this.tagName) //結果:BUTTON
})
body.appendChild(btn);
}
append() //執行append方法
2、使用jQuery為動態創建的對象綁定事件
var btn = document.createElement(‘button‘)
$(btn).attr("type","button")
$(btn).html(‘確定‘)
$(btn).click(function(){
console.log(this.tagName) //結果:BUTTON
})
$("body").append(btn)
給js動態創建的對象綁定事件