Eval () gets an object that is difficult to index

xiaoxiao2021-04-07  366

One of the issues of document object model (DOM) is: Sometimes you have to get you request.

Object is just pain. For example, there is a function to ask the user to transform

Which image: Which image is transformed?

You can use the following functions:

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.chese;

}

THE_IMAGE_Object.src = "Ant.gif";

}

Contains along with these image tags:

Please pay attention to a few line of statement like this:

THE_IMAGE_Object = Window.Document.Parrot;

It applies a parrot image object to a variable. Although it looks a bit

The child is strange, it has no problem in grammar. But when you have 100 instead of two

What should I do when the image? You have to write a big pile of if-thein-else statement, if

It's better to like this:

Function swaptwo ()

{

VAR THE_IMAGE = Prompt ("Change Parrot or Cheese", ""

Window.Document.The_Image.src = "Ant.gif";

}

Unfortunately, JavaScript will look for the name called THE_IMAGE instead of you.

The image of "Cheese" or "Parrot", so you got an error message: "

Haven't heard a object called the_image. "

Fortunately, Eval can help you get the 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 fills in "Parrot" in the prompt box, a word is created in the second line.

The string is Window.Document.Parrot. Then contain the third of Eval

Executive is: "Give me object window.document.parrot" - That is

The image object you want. Once you get this image object, you can put

Its SRC property is set to Ant.gif. Is it a little scared? Not. In fact, this is quite

Using, people often use it.

转载请注明原文地址:https://www.9cbs.com/read-132636.html

New Post(0)