toString()在使用传递参数时出错

toString() giving error when using to pass parameter

本文关键字:参数 出错 toString      更新时间:2023-09-26

toString在将其用作时给出错误cannot read property 'toString()' of undefined

document.getElementById('pMonth').addEventListener('click',function(){ calen(this.year.toString()+'-'+(this.currentMonth1-1).toString());},false);

但该代码在用作时运行良好

var tr=this.year.toString()+'-'+(this.currentMonth1-1).toString();
document.getElementById('pMonth').addEventListener('click',function(){ calen(tr);},false);

this.yearthis.CurrentMonth1是数值!!请告诉我哪里出了问题!

您需要将上下文绑定到事件处理程序,因为this将引用从document.getElementById('pMonth') 返回的DOM元素

所以你需要:

document.getElementById('pMonth').addEventListener(
   'click', 
   function(){
       calen(this.year.toString()+'-'+(this.currentMonth1-1).toString());
   }.bind(this),
   false
);