eval() 获取难以索引的对象

来源:互联网 发布:请问管家婆软件好用吗 编辑:程序博客网 时间:2024/05/24 07:08
文档对象模型(DOM)的问题之一是:有时你要获取你要求的
对象简直就是痛苦。例如,这里有一个函数询问用户要变换
哪个图象:变换哪个图象

 


  

你可以用下面这个函数:

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

连同这些image标记:

<img src="stuff3a/parrot.gif" name="parrot">
<img src="stuff3a/cheese.gif" name="cheese">

请注意象这样的几行语句:

      
the_image_object = window.document.parrot;

它把一个鹦鹉图象对象敷给了一个变量。虽然看起来有点
儿奇怪,它在语法上却毫无问题。但当你有100个而不是两个
图象时怎么办?你只好写上一大堆的 if-then-else语句,要是
能象这样就好了:

 

      
function swapTwo()
{
        var the_image = prompt("change parrot or cheese","");
        window.document.the_image.src = "ant.gif";
}

不幸的是, JavaScript将会寻找名字叫 the_image而不是你所希
望的"cheese"或者"parrot"的图象,于是你得到了错误信息:”
没听说过一个名为the_image的对象”。

 

还好,eval能够帮你得到你想要的对象。

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

如果用户在提示框里填入"parrot",在第二行里创建了一个字
符串即window.document.parrot. 然后包含了eval的第三
行意思是: "给我对象window.document.parrot" - 也就是
你要的那个图象对象。一旦你获取了这个图象对象,你可以把
它的src属性设为ant.gif. 有点害怕?用不着。其实这相当有
用,人们也经常使用它。