Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...