将addEventListener与方法中的函数一起使用

时间:2015-10-31 18:39:24

标签: javascript

我有一张九张照片的桌子,我还有九套:一张照片;文字;以及隐藏在屏幕左侧的音频控件。我试图这样做,以便当点击表格中的照片时,相应的设置从隐藏位置移动到网页的可见区域。
我问了这个问题并得到了一个有用的答案,关于如何使用onclick方法做到这一点,但因为我有九,因为我已经读过addeventlistener导致更清晰的代码,更经济,我一直试图这样做但没有运气。请查看我的代码并告诉我我缺少的内容,请提前感谢您的帮助。忽略onclick,因为一旦我得到addeventlistener工作,我将替换它。附:我正在尝试掌握JavaScript。

HTML代码(我还没有包含图片,文字,音频的代码,因为我知道他们使用onclick功能时很好:

...
<table>
   <tbody>
      <tr>
      <td><img onclick="sleepFunction(this)" src="01.jpg" height="180" width="120"></td>
      <td><img id = "02" src="02.jpg" height="180" width="120"/></td>
      <td><img id = "03" src="03.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img id = "04" src="04.jpg" height="180" width="120"/></td>
      <td><img id = "05" src="05.jpg" height="180" width="120"/></td>
      <td><img id = "06" src="06.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img id = "07" src="07.jpg" height="180" width="120"/></td>
      <td><img id = "08" src="08.jpg" height="180" width="120"/></td>
      <td><img id = "09" src="09.jpg" height="180" width="290"/></td>
      </tr>
   </tbody>
</table>    
...

这是JavaScript:

function slideShow (text, image, song) {
  this.text = text;
  this.image = image;
  this.song = song;
  this.xbutton = xbutton;
  this.moveLeft = function(){
    this.text.style.left = "357px";
    this.image.style.left = "851px";
    this.song.style.left = "450px";
    this.song.play();
    this.xbutton.style.left = "357px";
    }
  }

var sleep = new slideShow(document.getElementById("sleepText"),document.getElementById("sleepImage"), document.getElementById("sleepSong"), getElementById("xbutton"));

var sleepLeft = sleep.moveLeft();

document.getElementById("02").addEventListener("click", moveLeft);

1 个答案:

答案 0 :(得分:1)

看起来你很亲密。 moveLeft函数位于SlideShow实例中(您应该将该首字母大写),因此您需要将您的监听器更改为:

document.getElementById("02").addEventListener("click", sleep.moveLeft);

使用大写对象:

function SlideShow (text, image, song) {
  this.text = text;
  this.image = image;
  this.song = song;
  this.xbutton = xbutton;
  this.moveLeft = function(){
    this.text.style.left = "357px";
    this.image.style.left = "851px";
    this.song.style.left = "450px";
    this.song.play();
    this.xbutton.style.left = "357px";
    }
  }

var sleep = new SlideShow(document.getElementById("sleepText"),document.getElementById("sleepImage"), document.getElementById("sleepSong"), getElementById("xbutton"));

var sleepLeft = sleep.moveLeft();

document.getElementById("02").addEventListener("click", sleep.moveLeft);