当您单击文本But no success when you click me
时,会发生错误。我知道错误发生的原因。我的问题是什么是最好的解决办法?发生此错误的原因是,当单击mydiv
时调用x.a
,this
为mydiv
。我们怎样才能使x.a
成功运行时点击mydiv
?JavaScript中的'this'和addEventListener
<!DOCTYPE html>
<html>
<head>
\t <title></title>
</head>
<body>
\t <div id="mydiv">But no success when you click me</div>
\t <script>
\t \t var x = new Thing();
\t \t var y = document.getElementById('mydiv');
\t \t x.a();
\t \t y.addEventListener('click', x.a, false);
\t \t
\t \t function Thing() {
\t \t \t this.a=function() {
\t \t \t \t this.b();
\t \t \t }
\t \t \t this.b=function() {
\t \t \t \t alert('Success');
\t \t \t }
\t \t }
\t </script>
</body>
</html>
上述HTML文件位于http://globebop.com/intro/test/2.htm –
'x.a'没有绑定任何东西。用'()=> x.a()'替换'x.a'。 – 2017-02-24 07:23:15
对不起,Toraz。那是错的。 –