Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

Javascript change a picture when clicking

I wrote this function to change my pic what is the problem? my aim is when clicking on a pic toggle between 2 images if image p is showing by clicking shows me image p1

I have this in script:

  <script>
  function changeimage()
  {
   if(this.getElementById('myimage').src=="../../images/p1.gif")
   {

    document.getElementById('myimage').src="../../images/p.gif";
   }
  else
   {
    document.getElementById('myimage').src="../../images/p1.gif";
   }
  }
  </script>

in the html part I have these ones which are more than one picture but I set the whole of them with Id=myimage is it wrong to set the whole one same ID?:

<table width="100%">
<tr>
<td><img id='myimage' src="../../images/p1.gif" onclick="changeimage();setTable('table2');setTable('table2-2');check('table3');check('table3-3');check('table3-3-3');check('table4');check('table5');check('table6');check('table6-1');"></td>
    <td style="font-weight: bold;font-size:13;  font-family:arial,verdana;" width="25%">General Rule Options</td>
    <td valign="bottom" width="100%">

I have many rows in my tables like this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is the following line:

if(this.getElementById('myimage').src=="../../images/p1.gif")

In particular, it's the use of this. In your function this will refer to the window, and the window doesn't have a getElementById method. Use document like you have in the other cases:

if(document.getElementById('myimage').src=="../../images/p1.gif") {
    //...
}

And it looks like it should work fine. Alternatively, you can pass in an a reference to the clicked element when you call the event handler, and reference that instead of using getElementById. For example:

onclick="changeimage(this);"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...