One of the problems with the Document Object Model Hierarchy is that it's sometimes a pain to get to the object of your desire. For example, here is the function to ask the user for an image to swap:
swap which image?
You could use this function:
function swapOne()
{
var the_image = prompt("change parrot or cheese","");
var the_image_object;
if (the_image == "parrot")
{
the_image_object = window.document.parrot;
} else {
the_image_object = window.document.cheese;
}
the_image_object.src = "ant.gif";
}
With these image tags:
<img src="stuff3a/parrot.gif" name="parrot">
<img src="stuff3a/cheese.gif" name="cheese">
Note the lines that look like this:
the_image_object = window.document.parrot;
This assigns the image object parrot to a variable. Although it might look strange, it's perfectly legal. But what happens if you have 100 images instead of just two? You'd have to have a huge if-then-else
statement. It would be nice if you could just do this:
function swapTwo()
{
var the_image = prompt("change parrot or cheese","");
window.document.the_image.src = "ant.gif";
}
Unfortunately, JavaScript will look for an image named the_image rather than simply know you want the_image
to be "cheese," if the user typed "cheese" into the prompt box, or "parrot," if he or she typed "parrot." And thus you get an error saying something like, "Never heard of the object called the_image."
Luckily, eval can help you get at the image object you want.
function simpleSwap()
{
var the_image = prompt("change parrot or cheese","");
var the_image_name = "window.document." + the_image;
var the_image_object = eval(the_image_name);
the_image_object.src = "ant.gif";
}
If the user types "parrot" into the prompt box, the second line creates a string that looks like window.document.parrot. Then the eval on the third line says, "Give me the object window.document.parrot" which is the image object you want. And once you have that image object, you can change its source to ant.gif. Funky, no? It's actually pretty useful, and people do it a lot.
If you don't like eval(), there is another way to access hard-to-reach objects.
next page»