I have a webpage where I can click on it to add a image. If I then click on the image it makes it bigger and if I click again it resizes it back to the original size. If I then click somewhere else on the screen I can create another image and grow and shrink this开发者_JAVA百科 also by clicking on it. The problem is only the latest image can be resized by clicking even though none of the vars are being removed or changed. This is part of a game I am working on. I made a sample page with the least possible code to try it out and can be got here. http://johncleary.net/hg/ What I want is to be able to click on any image at any time and it will grow and shrink
From the code on your page, I see that you are using innerHTML += ...
to add new images - this isn't a very good thing, because it causes the browser to recreate all the inner elements every time you do so, and this could cause weird interactions with event handlers.
Consider using DOM methods to create and add elements, for example:
var e = document.createElement('img');
e.id = id;
e.onclick = pieceClicked; // No parameter required, this.id is available directly inside the function
...
board.appendChild(e);
Some other side notes:
You're using
xPix * yPix
as part of the ID: if you expect this to be unique, it may not be. For example,x = 500, y = 10
andx = 10, y = 500
will result in the same ID. How about just usingxPix + ',' + yPix
as a string by itself?The several lines in which you initialize
Pieces[id]
can be reduced to a simpler form using object notation:Pieces[id] = { Piece: ..., xPix: ..., yPix: ... }
.
精彩评论