Your images don't need an id attribute at all to work with the changeImage()
function that you've shown, since it seems just to be trying to swap the image source of whichever image had a mouseover
event. You can instead make use of the this
keyword to get a reference to the "current" image.
for (var i = 0; i < 400; i++) {
document.write("<img src=\"pic_bulboff.gif\" onmouseover=\"changeImage(this)\" width=\"20\" height=\"36\" />");
}
function changeImage(element) {
if (element.src.indexOf("bulbon")!=-1) {
element.src = "pic_bulboff.gif";
}
else {
element.src = "pic_bulbon.gif";
}
}
Note that normally the .match()
method is used with a regular expression to return an array of the parts of your source string that matched the regex, but if you just want to test whether your string matches a regex without worrying about exactly what the match was then you should use .test()
- or in your case since you're not using a regex at all it's probably more efficient to use .indexOf()
.
If you wanted a function to be able to process all of your images, you should give them a common class and then use the .getElementsByClassName()
method:
for (var i = 0; i < 400; i++) {
document.write('<img class="someClass" src="pic_bulboff.gif" onmouseover="changeImage(this)" width="20" height="36" />');
}
function someFunction() {
var elements = document.getElementsByClassName("someClass");
for (var i = 0; i < elements.length; i++) {
// do something with elements[i]
}
}
Note that you don't need to escape all the double-quotes in a string literal with backslashes if the string was quoted with single-quotes.
EDIT - In response to the comments:
The code above definitely works, as you can see here: http://jsfiddle.net/E5TGy/
Regarding the "correct" way to make it work with arrays, the whole concept is not appropriate to this problem. It doesn't make sense to have an array where the value stored at index i
is i
the way you do - if looking up myimage[7]
gives you 7
what's the point? The nearest thing to your code that will work is something like this:
document.write('<img id="' + myimage[i] +
'" src="pic_bulboff.gif" onmouseover="changeImage(' + myimage[i] +
')" width="20" height="36" />');
...and then your function would be:
function changeImage(elementID) {
var element = document.getElementById(elementID);
if (element.src.match("bulbon")) {
element.src = "pic_bulboff.gif";
}
else {
element.src = "pic_bulbon.gif";
}
}
As shown here: http://jsfiddle.net/qKksU/
myImage[i]
). You need to put the value of that variable there. And '0','1','2' are probably invalid ids, better start them with a letter. But you may not want to use ids at all, you could just use a class to target these images. Then you can do away with the document.write altogether and just have static HTML. – Thilo Nov 20 '12 at 4:34myindex[i]
will just return the same value asi
. @Thilo - id attributes can start with digits in html5. – nnnnnn Nov 20 '12 at 4:42