问答详情
源自:3-4 使用JS的构造函数创建菜单项对象

跟着老师打代码,游览器提示‘addEventListener’为空

(function(){

var Menubar=function(){

this.el=document.querySelector('#sidebar ul');

this.state='allClosed';

this.el.addEventListener('click',function(e){//提示‘addEventListener’为空

e.stopPropagation();

});

}

var Sidebar=function(eId,closeBarId){

this.state='opened';

this.el=document.getElementById(eId||'sidebar');

this.closeBarEl=document.getElementById('closeBarId'||'closeBar ');

var self=this;

this.menubar=new Menubar();

this.el.addEventListener('click',function(event){

if(event.target!==this.el){

self.triggerSwich();

}

});

};

Sidebar.prototype.close=function(){

console.log('关闭');

this.state='closed'

};

Sidebar.prototype.open=function(){

console.log('打开');

this.state='opened';

};

Sidebar.prototype.triggerSwich=function(){

if(this.state==='opened'){

this.close();

}else{

this.open();

}

};

var sidebar=new Sidebar();

})();

Uncaught TypeError: Cannot read property 'addEventListener' of null

提问者:China_好备胎 2016-12-08 10:07

个回答

  • 我是要成为全栈的男人
    2016-12-12 15:41:58

    打印一下 this.el 你就知道错在哪边了